package com.taptech.doufu.ui.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.taptech.doufu.bean.TagBean;
import com.taptech.doufu.constant.SPKey;
import com.taptech.doufu.constant.ShareType;
import com.taptech.doufu.constant.UmengEventName;
import com.taptech.doufu.event.EventBusNovelReadRecord;
import com.taptech.doufu.manager.UserLogManager;
import com.taptech.doufu.bean.base.ResponseBaseBean;
import com.taptech.doufu.bean.novel.NovelShowADInfoGsonBean;
import com.taptech.doufu.model.novel.bean.NovelDetailBean;
import com.taptech.doufu.ui.dialog.DoubleBtnTiptDialog;
import com.taptech.doufu.umeng.push.InAppMessageKey;
import com.taptech.doufu.umeng.push.PushManager;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.util.DensityUtil;
import com.taptech.doufu.util.ScreenBrightnessUtil;
import com.taptech.doufu.util.ShareUtil;
import com.taptech.doufu.util.ShareUtils;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.weex.module.TFCacheModule;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.adapter.NovelSectionDetailsAdapter;
import com.taptech.doufu.ui.adapter.ReadThemeAdapter;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.bean.TagsBean;
import com.taptech.doufu.bean.UserBean;
import com.taptech.doufu.bean.CollectExistGsonBean;
import com.taptech.doufu.bean.NovelSectionListBean;
import com.taptech.doufu.bean.novel.NovelPayInfoGsonBean;
import com.taptech.doufu.bean.novel.PayInfoBean;
import com.taptech.doufu.bean.CommentDataBean;
import com.taptech.doufu.services.CommentService;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.IntentKey;
import com.taptech.doufu.constant.SharedPreferencesKey;
import com.taptech.doufu.ui.dialog.TipSingleBtnDialog;
import com.taptech.doufu.event.BaseEventBusBean;
import com.taptech.doufu.event.EventBusCollect;
import com.taptech.doufu.event.EventBusConstant;
import com.taptech.doufu.event.EventBusOffline;
import com.taptech.doufu.event.EventBusReadUnLock;
import com.taptech.doufu.event.EventBusReadVerticalSpace;
import com.taptech.doufu.event.EventBusReadVolumeKey;
import com.taptech.doufu.ui.fragment.NovelChildFragments.SectionDetailsFragment;
import com.taptech.doufu.ui.fragment.NovelChildFragments.SectionDetailsLRFragmentNew;
import com.taptech.doufu.util.FileUtil;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.history.ReadHistoryUtil;
import com.taptech.doufu.services.history.ReadRecord;
import com.taptech.doufu.db.history.Read_DataBaseUtil;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.ui.view.readview.PageFactory;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.ui.view.theme.read.ReadTheme;
import com.taptech.doufu.ui.view.theme.read.ReadThemeHelper;
import com.taptech.doufu.ui.view.theme.ThemeType;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.MobileState;
import com.taptech.doufu.util.NoRepeatToast;
import com.taptech.doufu.util.StartActivityUtil;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.taptech.doufu.util.NotifyUtil;
import com.taptech.doufu.ui.view.GiftDialogManager;
import com.taptech.doufu.ui.view.VerticalViewPager;
import com.taptech.doufu.ui.view.WaitDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import rx.Observable;
import rx.functions.Action1;

public class NovelSectionDetailsActivity extends DiaobaoBaseActivity implements
        HttpResponseListener, ViewPager.OnPageChangeListener, OnClickListener,ReadThemeAdapter.OnClickItem
{
    private static final String TAG = NovelSectionDetailsActivity.class.getSimpleName();
    public static final int ENTER_NOVEL_TO_SWEEP_REQUEST = 1000;
    public static final int BACK_TO_NOVEL_DES_RESULT = 1001;
    public static final int ENTER_SELECT_READ_ANIMATION_REQUEST = 1002;
    public static final int ENTER_SELECT_READ_INDENT_REQUEST = 1003;
    public static final int CATLOG_PAGE_REQUEST = 1004;
    public static final String INTENT_KEY_OFFLINE_BOOK_KEY = "offline_book_key";
    public static final String SP_KEY_READ_TICKET_DIALOG_HAS_SHOW = "read_ticket_dialog_has_show_";
    Window window;
    TextView mChatCount;
    /** 小说内容容器 */
    public VerticalViewPager mNovelViewGroup;
    private NovelSectionDetailsAdapter detailsAdapter;

    public String getSectionId() {
        return sectionId;
    }

    private String sectionId = "";// 当前章节id
    public String novelId = "";// 此本小说的id
    private int articleItem;// 当前页码
    private int articleNum;// 章节总数
    private int sectionPosition = 0;
    int readArticleNum;//连续阅读章节数
    private String articleTitle;
    private String shareTitle;
    private boolean isSectionId;// 章节id是否存在
    public Map<String, HomeTopBean> mapContent;
    public Map<String, HomeTopBean> mapTopic;

    private PopupWindow mMorePopupWindow;
    private ImageView ivCollect,ivShare,ivReport,ivDetail;
    private TextView tvCollect,tvShare,tvReport,tvDetail;
    private LinearLayout llDialog;
    private View popup_reader_more_collect_line;
    private View popup_reader_more_share_line;
    private View popup_reader_more_detail_line;
    private boolean isCollect = false;// 是否为收藏
    private boolean isProtectEyes = false;

    public boolean isHas_fav() {
        return has_fav;
    }

    private boolean has_fav = true;

    public boolean isAutoPay = false;
    private boolean isFirstPageTurn = false;// 是否是第一次翻页

    public boolean isHintShow() {
        return isHintShow;
    }

    private boolean isHintShow = false;// 引导页是否显示
    private boolean isChapterProgressShow = false; //章节进度是否显示
    private String imageThumbUrl = null;
    /** 更多按钮 */
    private ImageView mPopMore;
    /** 更多按钮的父布局 */
    LinearLayout moreSelect;
    private View vsNotNetwork;// 无网布局
    private Button btnReload;// 重新加载
    private LinearLayout rlHint;// 首次使用提示布局
    /** mNightLine:作用不详，目前没用到  mTopLine:顶部布局的底部线条 */
    private View mTopLine;

    private RelativeLayout rlSecondLevelMenu;

    private boolean isClickNextOrPreview = true;// 是否是点击上下章按钮（改值是为了应对奇葩需求，要求翻页把导航栏弹回去，点击翻页就不用弹回去。。。）
    public boolean isClickNOrPScroll;// 是否是点击上下章按钮（由于初始化章节时需滑动1个单位初始化透明布局，用此来限制导航栏不回弹）
    private List<Map<String, String>> mCommentListNum = new ArrayList<Map<String, String>>();
    /** 加载等待对话框 */
    private WaitDialog dialog;
    // 手机状态
    private MobileState mobileState;
    private boolean isLogin;// 登录状态
    private boolean isYouthModel;

    private List<NovelSectionListBean> catalogList;


    /** 返回按钮 */
    @SuppressLint("NewApi")
    private SharedPreferences mPreferences;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Read_DataBaseUtil mRead_DataBaseUtil;
    private ReadRecord readRecord;
    private SparseArray<String> mNovelDetailIds;

    public SparseArray<String> getmNovelDetailIds() {
        return mNovelDetailIds;
    }

    private TextView commentCount;
    // 顶部和底部栏是否可见
    public boolean isTopAndBottomVisiable = true;
    private String tagStrings;
    private String tagStringsArray[];
    SectionDetailsLRFragmentNew sectionDetailsLRFragmentNew;
    FrameLayout novel_left_to_right;

    private View layContent,lay;
    //一级菜单
    private SeekBar seekbarChapter;  //章节进度条
    private SeekBar seekbarFontSize;  //字体大小进度条
    private SeekBar seekbarLight;  //亮度进度条
    private LinearLayout llPreView; //上一章
    private LinearLayout llNextView;//下一章
    private LinearLayout llCatalog;  //目录
    private LinearLayout llDayAndNight;//白天夜间切换
    private LinearLayout llReadSet; //阅读设置
    private LinearLayout llNovelComment;//评论
    private LinearLayout llReadMoreSet;//更多阅读设置
    private LinearLayout llReadAnimation;//阅读动画
    private LinearLayout llPlay;//自动播放
    private LinearLayout llEyes;//护眼模式
    private RelativeLayout rlRealOffLine;// 离线
    private ImageView ivBack;
    private LinearLayout llOther;//其他操作
    private RelativeLayout giftLayout; //礼物
    private LinearLayout llLightAdd; //增加亮度
    private LinearLayout llLightSub; //降低亮度
    private LinearLayout llSysLight; //系统亮度
    private TextView tvSysLight;
    private LinearLayout llFontSizeAdd; //增加字体大小
    private LinearLayout llFontSizeSub; //减小字体大小
    private RecyclerView recycleView;//主题选择栏
    private View eyesView;//护眼模式的蒙版
    private LinearLayout llChapterProgress;//章节进度
    private TextView tvChapterProgress,tvChapterTitle;
    private ImageView ivBackChapter;
    private ReadThemeAdapter adapter;
    private ImageView ivOffLine,ivGift,ivLightSub,ivLightAdd,ivFontSizeSub,ivFontSizeAdd,ivFlip,ivEyes,ivPlay,ivReadMore,
            ivPre,ivNext,ivCatalog,ivNight,ivSet,ivComment; //图标
    private TextView tvFlip,tvEyes,tvPlay,tvReadMore,tvCatalog,tvNight,tvSet,tvComment;
    private View lineOne,lineTwo,lineThree;
    private View viewPlay;
    private LinearLayout llAutoPlay,llSpeedSub,llSpeedAdd,llExitPlay;
    private View playLineOne,playLineTwo,playLineThree,playLineFour;
    private TextView tvPlaySpeedSub,tvPlaySpeedAdd,tvPlayPage,tvPlayLine,tvExitPlay;
    private SeekBar seekbarPlay;
    private TextView floatBtnCollect;  //收藏浮标
    private int dx;
    private int dy;
    private int touchX;
    private int touchY;
    private int verticalY;

    private TextView tvOfficialUsed,tvOfficialUsable,tvGiveUsed,tvGiveUsable,tvTipSelectAuto;
    private ImageView ivTipSelectAuto;
    private View readTicketDialog,llSure;

    private FrameLayout flGDT,flGDTContent;

    public void setVerticalY(int verticalY) {
        this.verticalY = verticalY;
    }

    private boolean isClickView;

    private boolean isTurnOnVolumeKey;
    private int backPosition = -1;

    /** mTopLayout:顶部布局  mBottomLayout:底部布局 */
    private RelativeLayout mTopLayout, mBottomLayout;

    public int getMonthTicketSum() {
        return monthTicketSum;
    }

    private int monthTicketSum = 0;

    public void setCurCapter(int capter) {
        this.realIdsPos = capter-1;
        setChapterProgress();
        this.articleItem = capter;
    }

    private long startReadTime;


    /**
     * 设置章节总数
     * @param articleNum
     */
    public void setArticleNum(int articleNum) {
        this.articleNum = articleNum;
    }

    /**
     * 设置文章标题
     * @param title
     */
    public void setArticleTitle(String title) {
        if (!TextUtils.isEmpty(title)) {
            articleTitle = title;
        }
    }

    public void addReadArticleNum() {
        this.readArticleNum = this.readArticleNum+1;
    }

    public static final String TAG_FINISH_ACTIVITY = "finish_novel_read_activity"; //关闭页面
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinishActivity(BaseEventBusBean event){
        if (event != null&&event.getTag()!=null && event.getTag().equals(TAG_FINISH_ACTIVITY)) {
            finish();

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCollectState(EventBusCollect event) {
        if (event != null&& event.getTag() !=null && event.getTag().equals(EventBusCollect.tag)) {
            has_fav = event.isHasCollect();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setUnLock(EventBusReadUnLock event) {
        if (event != null&& event.getTag() !=null && event.getTag().equals(EventBusReadUnLock.tag)) {
            setScreenUnLock(event.isUnLock());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateReadSpace(EventBusReadVerticalSpace event){
        if (event != null&& event.getTag() !=null && event.getTag().equals(EventBusReadVerticalSpace.tag)) {
            setLineSpace(event.getSpace());
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setVolumeKey(EventBusReadVolumeKey event){
        if (event != null&& event.getTag() !=null && event.getTag().equals(EventBusReadVolumeKey.tag)) {
            isTurnOnVolumeKey = event.isTurnVolumeKey();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOffLineUpdate(EventBusOffline eventBusOffline) {
        if (eventBusOffline != null && eventBusOffline.getTag() != null &&
                eventBusOffline.getTag().equals(EventBusOffline.tag)) {
            if (!TextUtil.isEmpty(eventBusOffline.getOffline())) {
                if(!isOffLine){
                    isChangeOffline = true;
                }
                offline = eventBusOffline.getOffline();
                sectionDetailsLRFragmentNew = null;
                mNovelDetailIds = null;
                topicBean = null;
                mapContent.clear();
                initData();
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        boolean isUnLock = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_PAGE_READ_UNLOCK_SCREEN,
                this, false);
        setScreenUnLock(isUnLock);
        setContentView(R.layout.activity_novel_section_details);
        FileUtil.getInstance().createDir();
        isLogin = AccountService.getInstance().isLogin();
        mapContent = new HashMap<>();
        mapTopic = new HashMap<>();
        isProtectEyes = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_PAGE_READ_PROTECT_EYES,
                this, false);
        isTurnOnVolumeKey = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_PAGE_READ_VOLUME_KEY,
                this, false);
        String pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, this, "");
        if (pwd != null && pwd.length() > 0) {
            isYouthModel = true;
        }
        initUI();
        initState();
        initData();
        setReadTheme(ReadThemeHelper.getReadTheme());

        int readTime = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SPKey.NOVEL_READ_TIMES+novelId,this,0);
        if (readTime >= 0) {
            DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SPKey.NOVEL_READ_TIMES+novelId,readTime+1,this);
        }

        if (!isPageTurningVertical() && sectionDetailsLRFragmentNew == null && !TextUtils.isEmpty(sectionId)) {
            sectionDetailsLRFragmentNew = SectionDetailsLRFragmentNew.newInstance(sectionId, novelId);
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.novel_left_to_right, sectionDetailsLRFragmentNew);
            fragmentTransaction.commit();
        }
        UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_NOVEL_READ,novelId);
        PushManager.getInstance().inAppMessage(this,InAppMessageKey.READER);
    }

    private void initReadTicketTipUI() {
        tvOfficialUsed = (TextView) findViewById(R.id.tvOfficialUsed);
        tvOfficialUsable = (TextView) findViewById(R.id.tvOfficialUsable);
        tvGiveUsed = (TextView) findViewById(R.id.tvGiveUsed);
        tvGiveUsable = (TextView) findViewById(R.id.tvGiveUsable);
        tvTipSelectAuto = (TextView) findViewById(R.id.tvTipSelectAuto);
        ivTipSelectAuto = (ImageView) findViewById(R.id.ivTipSelectAuto);
        readTicketDialog = findViewById(R.id.readTicketDialog);
        llSure = findViewById(R.id.llSure);
        llSure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tempAutoPayState){
                    //直接购买
                    if (isPageTurningVertical()){
                        if(mNovelViewGroup != null && detailsAdapter != null &&
                                detailsAdapter.getCount() > 0 &&
                                detailsAdapter.getCount() > mNovelViewGroup.getCurrentItem()&&
                                mNovelViewGroup.getCurrentItem()+1 != detailsAdapter.getCount()) {
                            SectionDetailsFragment fragment = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
                            if (fragment != null) {
                                fragment.setAutoPay(tempAutoPayState);
                                fragment.buyChapter();
                            }
                        }
                    }else{
                        //更新自动阅读状态
                        if (sectionDetailsLRFragmentNew != null) {
                            sectionDetailsLRFragmentNew.setAutoPay(tempAutoPayState);
                            sectionDetailsLRFragmentNew.buyChapter();
                        }
                    }
                }
                readTicketDialog.setVisibility(View.GONE);
            }
        });
        ivTipSelectAuto.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setAutoPayState();
            }
        });
        tvTipSelectAuto.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setAutoPayState();
            }
        });
    }

    private boolean tempAutoPayState;

    private void setAutoPayState(){
        tempAutoPayState = !tempAutoPayState;
        if (tempAutoPayState){
            ivTipSelectAuto.setImageResource(R.drawable.reading_reminder_select_st);
        }else{
            ivTipSelectAuto.setImageResource(R.drawable.reading_reminder_select);
        }
    }

    public boolean isShowTicketDialog() {
        if (payInfoBean!=null &&
                payInfoBean.getTicketCountInfo()!=null &&
                payInfoBean.getTicketCountInfo().isShow_dialog()){
            boolean isHasShow = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SP_KEY_READ_TICKET_DIALOG_HAS_SHOW+novelId,this,false);
            if (isHasShow){
                return false;
            }else {
                return true;
            }
        }else{
            return false;
        }
    }

    public void showReadTicketDialog() {
        DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SP_KEY_READ_TICKET_DIALOG_HAS_SHOW+novelId,true,this);
        if (payInfoBean != null && payInfoBean.getTicketCountInfo() != null) {
            tvOfficialUsed.setText(String.valueOf(payInfoBean.getTicketCountInfo().getOfficial_used()));
            tvOfficialUsable.setText(String.valueOf(payInfoBean.getTicketCountInfo().getOfficial_usable()));
            tvGiveUsed.setText(String.valueOf(payInfoBean.getTicketCountInfo().getAuthor_give_used()));
            tvGiveUsable.setText(String.valueOf(payInfoBean.getTicketCountInfo().getAuthor_give_usable()));
        }
        readTicketDialog.setVisibility(View.VISIBLE);
        tempAutoPayState = isAutoPay;
        if (isAutoPay){
            ivTipSelectAuto.setImageResource(R.drawable.reading_reminder_select_st);
        }else{
            ivTipSelectAuto.setImageResource(R.drawable.reading_reminder_select);
        }

    }

    private void initUI() {
        initReadTicketTipUI();
        floatBtnCollect = (TextView) findViewById(R.id.floatBtnCollect);
        flGDT = (FrameLayout) findViewById(R.id.flGDT);
        flGDTContent = (FrameLayout) findViewById(R.id.flGDTContent);
        // 夜间模式需要修改
        mPopMore = (ImageView) findViewById(R.id.novel_details_other_more);
        mTopLayout = (RelativeLayout) findViewById(R.id.novel_details_top_layout);
        mBottomLayout = (RelativeLayout) findViewById(R.id.rlFirstLevelMenu);
        rlSecondLevelMenu = (RelativeLayout) findViewById(R.id.rlSecondLevelMenu);
        setSecondMuneVisiable(false);
        mTopLine = findViewById(R.id.novel_details_top_line);
        rlHint = (LinearLayout) findViewById(R.id.rl_novel_section_details_test_hint);
        mNovelViewGroup = (VerticalViewPager) findViewById(R.id.activity_novel_section_viewgroup);// NovelDetailsScroll
        novel_left_to_right = (FrameLayout) findViewById(R.id.novel_left_to_right);
        layContent = findViewById(R.id.layContent);
        layContent.setPadding(0, ScreenUtil.getStatusHeight(this),0,0);
        lay = findViewById(R.id.lay);
        if (isPageTurningVertical()) {
            novel_left_to_right.setVisibility(View.GONE);
            mNovelViewGroup.setVisibility(View.VISIBLE);
        } else {
            novel_left_to_right.setVisibility(View.VISIBLE);
            mNovelViewGroup.setVisibility(View.GONE);
        }
        commentCount = (TextView) findViewById(R.id.novel_section_des_count);
        giftLayout = (RelativeLayout) findViewById(R.id.giftLayout);
        vsNotNetwork = findViewById(R.id.vs_activity_novel_section_details_test);
        btnReload = (Button) vsNotNetwork.findViewById(R.id.btn_common_novel_no_network);

        seekbarChapter = (SeekBar) findViewById(R.id.seekbarChapter);
        seekbarLight = (SeekBar) findViewById(R.id.seekbarLight);
        seekbarFontSize = (SeekBar) findViewById(R.id.seekbarFontSize);
        llPreView = (LinearLayout) findViewById(R.id.llPreView);
        llNextView = (LinearLayout) findViewById(R.id.llNextView);
        llCatalog = (LinearLayout) findViewById(R.id.llCatalog);
        llDayAndNight = (LinearLayout) findViewById(R.id.llDayAndNight);
        llReadSet = (LinearLayout) findViewById(R.id.llReadSet);
        llNovelComment = (LinearLayout) findViewById(R.id.llNovelComment);
        llOther = (LinearLayout) findViewById(R.id.llOther);
        llReadMoreSet = (LinearLayout) findViewById(R.id.llReadMoreSet);
        llReadAnimation = (LinearLayout) findViewById(R.id.llReadAnimation);
        llPlay = (LinearLayout) findViewById(R.id.llPlay);
        llEyes = (LinearLayout) findViewById(R.id.llEyes);
        eyesView = findViewById(R.id.eyesView);
        rlRealOffLine = (RelativeLayout) findViewById(R.id.rlRealOffLine);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        llLightAdd = (LinearLayout) findViewById(R.id.llLightAdd);
        llLightSub = (LinearLayout) findViewById(R.id.llLightSub);
        llSysLight = (LinearLayout) findViewById(R.id.llSysLight);
        llFontSizeAdd = (LinearLayout) findViewById(R.id.llFontSizeAdd);
        llFontSizeSub = (LinearLayout) findViewById(R.id.llFontSizeSub);
        llChapterProgress = (LinearLayout) findViewById(R.id.llChapterProgress);
        llChapterProgress.setVisibility(View.GONE);
        tvSysLight = (TextView) findViewById(R.id.tvSysLight);
        tvChapterProgress = (TextView) findViewById(R.id.tvChapterProgress);
        tvChapterTitle = (TextView) findViewById(R.id.tvChapterTitle);
        ivBackChapter = (ImageView) findViewById(R.id.ivBackChapter);

        //主题
        ivOffLine = (ImageView) findViewById(R.id.ivOffLine);
        ivGift = (ImageView) findViewById(R.id.ivGift);
        ivLightSub = (ImageView) findViewById(R.id.ivLightSub);
        ivLightAdd = (ImageView) findViewById(R.id.ivLightAdd);
        ivFontSizeSub = (ImageView) findViewById(R.id.ivFontSizeSub);
        ivFontSizeAdd = (ImageView) findViewById(R.id.ivFontSizeAdd);
        ivFlip = (ImageView) findViewById(R.id.ivFlip);
        ivEyes = (ImageView) findViewById(R.id.ivEyes);
        ivPlay = (ImageView) findViewById(R.id.ivPlay);
        ivReadMore = (ImageView) findViewById(R.id.ivReadMore);
        ivPre = (ImageView) findViewById(R.id.ivPre);
        ivNext = (ImageView) findViewById(R.id.ivNext);
        ivCatalog = (ImageView) findViewById(R.id.ivCatalog);
        ivNight = (ImageView) findViewById(R.id.ivNight);
        ivSet = (ImageView) findViewById(R.id.ivSet);
        ivComment = (ImageView) findViewById(R.id.ivComment);
        tvFlip = (TextView) findViewById(R.id.tvFlip);
        tvEyes = (TextView) findViewById(R.id.tvEyes);
        tvPlay = (TextView) findViewById(R.id.tvPlay);
        tvReadMore = (TextView) findViewById(R.id.tvReadMore);
        tvCatalog = (TextView) findViewById(R.id.tvCatalog);
        tvNight = (TextView) findViewById(R.id.tvNight);
        tvSet = (TextView) findViewById(R.id.tvSet);
        tvComment = (TextView) findViewById(R.id.tvComment);
        //分割线
        lineOne = findViewById(R.id.lineOne);
        lineTwo = findViewById(R.id.lineTwo);
        lineThree = findViewById(R.id.lineThree);
        recycleView = (RecyclerView) findViewById(R.id.recycleView);
        //自动阅读UI
        viewPlay = findViewById(R.id.viewPlay);
        llAutoPlay = (LinearLayout) findViewById(R.id.llAutoPlay);
        llSpeedSub = (LinearLayout) findViewById(R.id.llSpeedSub);
        llSpeedAdd = (LinearLayout) findViewById(R.id.llSpeedAdd);
        llExitPlay = (LinearLayout) findViewById(R.id.llExitPlay);
        playLineOne =  findViewById(R.id.playLineOne);
        playLineTwo =  findViewById(R.id.playLineTwo);
        playLineThree =  findViewById(R.id.playLineThree);
        playLineTwo =  findViewById(R.id.playLineTwo);
        playLineFour =  findViewById(R.id.playLineFour);
        tvPlaySpeedSub = (TextView) findViewById(R.id.tvPlaySpeedSub);
        tvPlaySpeedAdd = (TextView) findViewById(R.id.tvPlaySpeedAdd);
        tvPlayPage = (TextView) findViewById(R.id.tvPlayPage);
        tvPlayLine = (TextView) findViewById(R.id.tvPlayLine);
        tvExitPlay = (TextView) findViewById(R.id.tvExitPlay);
        seekbarPlay = (SeekBar) findViewById(R.id.seekbarPlay);
        setListen();
    }



    public void onCloseGDT(View view){
        flGDTContent.removeAllViews();
        flGDT.setVisibility(View.GONE);
    }



    private void setProtectEyesView() {
        if(isProtectEyes){
            ivEyes.setImageResource(R.drawable.read_eye_st);
            tvEyes.setTextColor(getResources().getColor(R.color.top_title_red_color));
            eyesView.setVisibility(View.VISIBLE);
        }else{
            ivEyes.setImageResource(ReadThemeHelper.getReadTheme().getSecondMenuTheme().getProtectEyesImage());
            tvEyes.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getSecondMenuTheme().getFontColor()));
            eyesView.setVisibility(View.GONE);
        }
    }


    private void setChapterProgress() {
        if (catalogList != null && catalogList.size() > 0 && seekbarChapter!=null) {
            seekbarChapter.setMax(catalogList.size());
            seekbarChapter.setProgress(realIdsPos);
        }
    }

    private void setListen() {
        floatBtnCollect.setOnClickListener(this);
        mNovelViewGroup.setOnPageChangeListener(this);
        rlHint.setOnClickListener(this);
        btnReload.setOnClickListener(this);
        llPreView.setOnClickListener(this);
        llNextView.setOnClickListener(this);
        llCatalog.setOnClickListener(this);
        llDayAndNight.setOnClickListener(this);
        llReadSet.setOnClickListener(this);
        llNovelComment.setOnClickListener(this);
        rlRealOffLine.setOnClickListener(this);
        llReadMoreSet.setOnClickListener(this);
        llReadAnimation.setOnClickListener(this);
        llPlay.setOnClickListener(this);
        llEyes.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        giftLayout.setOnClickListener(this);
        llOther.setOnClickListener(this);
        llLightSub.setOnClickListener(this);
        llSysLight.setOnClickListener(this);
        llLightAdd.setOnClickListener(this);
        llFontSizeSub.setOnClickListener(this);
        llFontSizeAdd.setOnClickListener(this);
        mBottomLayout.setOnClickListener(this);
        llChapterProgress.setOnClickListener(this);
        rlSecondLevelMenu.setOnClickListener(this);
        llExitPlay.setOnClickListener(this);
        tvPlayPage.setOnClickListener(this);
        tvPlayLine.setOnClickListener(this);
        llSpeedSub.setOnClickListener(this);
        llSpeedAdd.setOnClickListener(this);
        llAutoPlay.setOnClickListener(this);

        viewPlay.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                boolean flag = false;
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        dx = (int) event.getX();
                        dy = (int) event.getY();
                        touchX = dx;
                        touchY = dy;
                        isClickView = true;
                        flag = true;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        //移动
                        if (dx - (int)event.getX() > 2 || (int)event.getX() - dx > 2 ||
                                dy - (int)event.getY() > 2 || (int)event.getY() - dy > 2) {
                            if(isClickView){
                                sectionDetailsLRFragmentNew.waitPlay();
                            }
                            isClickView = false;
                            if (isAutoPlayLine) {
                                sectionDetailsLRFragmentNew.setAutoPlayProgress((int)event.getY()-touchY);
                                touchY = (int)event.getY();
                                touchX = (int) event.getX();
                            }else{

                            }
                        }
                        flag = true;
                        break;
                    case MotionEvent.ACTION_UP:
                        if (isClickView) {
                            setAutoPlayMuneVisiable(!isAutoPlayMuneVisiable);
                        }else{
                            sectionDetailsLRFragmentNew.restartPlay();
                        }
                        flag = true;
                        break;
                }

                return flag;
            }
        });
        int progress = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_LIGHT_STATE,
                this, ScreenBrightnessUtil.getScreenBrightness(this));
        isSysLight = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_SYS_LIGHT,
                this, true);
        if (isSysLight) {
            ScreenBrightnessUtil.setBrightness(this, -1);
            tvSysLight.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getSecondMenuTheme().getSysLightFCSelect()));
        }else{
            ScreenBrightnessUtil.setBrightness(this, progress);
            tvSysLight.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getSecondMenuTheme().getSysLightFCUnSelect()));
        }
        seekbarLight.setProgress(progress);
        seekbarLight.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                ScreenBrightnessUtil.setBrightness(NovelSectionDetailsActivity.this, progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSysLight = false;
                tvSysLight.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getSecondMenuTheme().getSysLightFCUnSelect()));
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_SYS_LIGHT, false, NovelSectionDetailsActivity.this);
                DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_LIGHT_STATE,
                        seekBar.getProgress(),NovelSectionDetailsActivity.this);

            }
        });

        int fontProgress = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_FONT_SIZE_STATE,
                this,1);
        seekbarFontSize.setProgress(fontProgress);
        seekbarFontSize.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }


            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                updateTextSize(progressToFontSize(seekBar.getProgress()));
                DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_FONT_SIZE_STATE,
                        seekBar.getProgress(),getThisActivity());
            }
        });
        seekbarChapter.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    updateChapterProgress(progress);
                }else if(isCanJumpChapter){  //点击回退
                    isCanJumpChapter = false;
                    updateChapterProgress(progress);
                    if (isPageTurningVertical()){
                        isClickNextOrPreview = true;
                        isClickNOrPScroll = true;
                        jumpToVertical(matchProgress(seekBar.getProgress()));
                    }else{
                        jumpToHorizontal(matchProgress(seekBar.getProgress()),getChapterTitle(seekBar.getProgress()));
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isChapterProgressShow = true;
                if (backPosition == -1) {
                    backPosition = realIdsPos;
                }
                if (isPageTurningVertical()){
                    isClickNextOrPreview = true;
                    isClickNOrPScroll = true;
                    jumpToVertical(matchProgress(seekBar.getProgress()));
                }else{
                    jumpToHorizontal(matchProgress(seekBar.getProgress()),getChapterTitle(seekBar.getProgress()));
                }
            }
        });
        int speed = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_AUTO_READ_ALL_TIME, this, 20);
        seekbarPlay.setProgress(speed);
        seekbarPlay.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser){
                    if (sectionDetailsLRFragmentNew != null) {
                        int speed = formatSpeed(progress);
                        sectionDetailsLRFragmentNew.updateSpeed(speed*1000);
                        DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_AUTO_READ_ALL_TIME,progress,
                                NovelSectionDetailsActivity.this);
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (sectionDetailsLRFragmentNew != null) {
                    int speed = formatSpeed(seekBar.getProgress());
                    sectionDetailsLRFragmentNew.updateSpeed(speed*1000);
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_AUTO_READ_ALL_TIME,seekBar.getProgress(),
                            NovelSectionDetailsActivity.this);
                }
            }
        });
        ivBackChapter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(seekbarChapter!=null && seekbarChapter.getMax()>=backPosition && backPosition>-1){
                    isCanJumpChapter = true;
                    seekbarChapter.setProgress(backPosition);
                }
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recycleView.setLayoutManager(manager);
        adapter = new ReadThemeAdapter(this, ReadThemeHelper.getReadTheme(),this);
        recycleView.setAdapter(adapter);
    }

    private int formatSpeed(int progress) {
        int temp = 120 - progress;
        if (temp < 5) {
            return 5;
        }
        return temp;
    }

    private void hideChapterProgress() {
        isChapterProgressShow = false;
        llChapterProgress.setVisibility(View.GONE);
        backPosition = -1;
    }

    boolean isCanJumpChapter = false;
    private void updateChapterProgress(int progress){
        tvChapterProgress.setText(formatProgress(progress));
        tvChapterTitle.setText(getChapterTitle(progress));
        llChapterProgress.setVisibility(View.VISIBLE);

    }

    private int matchProgress(int progress){
        if (progress <= 0) {
            progress = 0;
        } else if (catalogList!=null && progress >= catalogList.size()) {
            progress = catalogList.size()-1;
        }
        return progress;
    }

    private String getChapterTitle(int progress) {
        String title = "";
        if (catalogList != null && catalogList.size() > 0) {
            if (progress <= 0) {
                title = catalogList.get(0).getTitle();
            } else if (progress >= catalogList.size()) {
                title = catalogList.get(catalogList.size()-1).getTitle();
            }else{
                title = catalogList.get(progress).getTitle();
            }
        }
        return title;
    }

    private String formatProgress(int progress){
        String strProgress ;
        if (catalogList != null) {
            if (progress <= 0) {
                strProgress = "0%";
            } else if (progress >= catalogList.size()) {
                strProgress = "100%";
            }else{
                strProgress = PageFactory.formatDouble(progress/(double)catalogList.size()*100)+"%";
            }
            return strProgress;
        }else{
            return "0%";
        }

    }

    private void jumpToHorizontal(int pos, String title) {
        realIdsPos = pos;
        articleItem = realIdsPos + 1;
        if (sectionDetailsLRFragmentNew != null) {
            sectionDetailsLRFragmentNew.setCapterTitle(title);
            sectionDetailsLRFragmentNew.jumpToCapter(realIdsPos+1);
        }
    }

    private void jumpToVertical(int pos) {
        try {
            realIdsPos = pos;
            articleItem = realIdsPos + 1;
            mNovelViewGroup.setCurrentItem(realIdsPos,false);
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }

    public static int progressToFontSize(int progress) {
        int fontSize;
        if (progress == 0) {
            fontSize = 15;
        }else if(progress == 1){
            fontSize = 17;
        }else if(progress == 2){
            fontSize = 19;
        } else if (progress == 3) {
            fontSize = 21;
        } else if (progress == 4) {
            fontSize = 23;
        }else{
            fontSize = 25;
        }
        return DensityUtil.sp2px(WeMediaApplication.applicationContext, fontSize);
    }

    public void setSurplusTotal(int cutPrice) {
        if (payInfoBean != null) {
            payInfoBean.setSurplusTotal((payInfoBean.getSurplusTotal()-(int)(cutPrice/payInfoBean.getDiscount())));
        }
    }

    public PayInfoBean getPayInfoBean() {
        return payInfoBean;
    }

    private PayInfoBean payInfoBean;



    public void getPayInfo() {
        ApiClient.getInstance().setUseCache(false).getService().getNovelPayInfo(novelId)
                .compose(RxJavaHelper.<NovelPayInfoGsonBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<NovelPayInfoGsonBean>(){
                    @Override
                    public void onNext(NovelPayInfoGsonBean novelPayInfoGsonBean) {
                        super.onNext(novelPayInfoGsonBean);
                        if (novelPayInfoGsonBean != null) {
                            payInfoBean = novelPayInfoGsonBean.getData();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }


    /**
     * 状态同步:电量、时间
     */
    private void initState() {
        mobileState = MobileState.getInstance();
        mobileState.initListenMobileState(new MobileState.StateChangeListener() {
            @Override
            public void onStateChanged() {
                if(mNovelViewGroup != null && detailsAdapter != null && detailsAdapter.getCount() > 0 && mNovelViewGroup.getCurrentItem()+1 != detailsAdapter.getCount()) {
                    SectionDetailsFragment fragment = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
                    if (fragment != null) {
                        fragment.setMobileState(mobileState);
                    }
                }
            }
        });
    }

    private boolean isFromCatalog = false;

    public boolean isFromCatalog() {
        return isFromCatalog;
    }

    public void setFromCatalog(boolean fromCatalog) {
        isFromCatalog = fromCatalog;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        refreshData(intent);
    }

    private void refreshData(Intent intent) {
        if (intent == null) {
            return;
        }
        novelId = intent.getStringExtra(Constant.ARTICLE_NOVELID);
        sectionId = intent.getStringExtra(Constant.ARTICLE_ID);
        String capterTitle = intent.getStringExtra(Constant.TITLE);
        if (mNovelDetailIds != null && mNovelDetailIds.size() > 0){
            for (int i = 0 ; i < mNovelDetailIds.size() ; i++){
                if(!TextUtils.isEmpty(sectionId)&&
                        mNovelDetailIds.get(i)!=null&&
                        sectionId.equals(mNovelDetailIds.get(i))){
                    isFromCatalog = true;
                    realIdsPos = i;
                    articleItem = realIdsPos + 1;
                    if(isPageTurningVertical()){
                        mNovelViewGroup.setCurrentItem(realIdsPos);
                    }else{
                        if (sectionDetailsLRFragmentNew != null) {
                            sectionDetailsLRFragmentNew.setCapterTitle(capterTitle);
                            sectionDetailsLRFragmentNew.jumpToCapter(realIdsPos+1);
                        }
                    }
                }
            }
        }
    }



    private String offline ;
    private boolean isChangeOffline = false;//从在线变离线
    private JSONObject topicObject ;
    private JSONArray catelogArray ;
    public JSONArray articlesArray ;
    private String offlineKey;

    public String getOffline() {
        return offline;
    }

    private void initData() {
        /**
         * 保存数据，显示历史列表
         */
        try {
            mRead_DataBaseUtil = new Read_DataBaseUtil(NovelSectionDetailsActivity.this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        moreSelect = (LinearLayout) findViewById(R.id.layout_reader_toolbar_top_more);
        makeMorePopupWindow();
        dialog = new WaitDialog(this, R.style.waitDialog, "");
        dialog.setCanceledOnTouchOutside(false);
        // 记录最后一次阅读的相关信息
        mPreferences = getSharedPreferences(Constant.sharedPre_novel, 0);

        // 点击的item位置，用于首位章节做判断
        Intent intent = getIntent();
        //获取章节数据
        sectionId = intent.getStringExtra(Constant.ARTICLE_ID);
        monthTicketSum = intent.getIntExtra(Constant.MONTH_TICKET_SUM,0);
        //获取上次阅读的id
        readID = sectionId;
        //获取小说id
        novelId = intent.getStringExtra(Constant.ARTICLE_NOVELID);
        getPayInfo();
        getIsCollect();
        //如果小说id为空，取本地值
        if (TextUtils.isEmpty(novelId)) {
            novelId = mPreferences.getString(Constant.ARTICLE_NOVELID, "");
        }
        cancelReadMark(novelId);
        if (TextUtils.isEmpty(sectionId)) {
            sectionId = "";
        }
        offlineKey = getIntent().getStringExtra(INTENT_KEY_OFFLINE_BOOK_KEY);
        if (!TextUtil.isEmpty(offlineKey)) {
            dialog.show();
            Observable.create((Observable.OnSubscribe<String>) subscriber -> {
                String offline = TFCacheModule.getValue(offlineKey).toString();
                subscriber.onNext(offline);
            }).compose(RxJavaHelper.<String>observeOnMainThread(this))
            .subscribe(str -> {
                initOfflineData(str);
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            });
        }else{
            dialog.show();
            isOffLine = false;
            HomeMainServices.getInstance().loadNovelSectionListNew(this, novelId, null);
        }
    }


    private void cancelReadMark(String id){
        ApiClient.getInstance().getService().cancelReadMark(id,Constant.OBJECT_TYPE_NOVEL)
                .compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread(this))
                .subscribe(new BaseSubscriber<ResponseBaseBean>(){
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onNext(ResponseBaseBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                    }
                });
    }

    private void getIsCollect() {
        //加载自己是否收藏过接口
        if (AccountService.getInstance().isLogin()) {
            if (!TextUtils.isEmpty(novelId)) {
                ApiClient.getInstance().setUseCache(false).getService().judgeCollectExist(novelId,"5")
                        .compose(RxJavaHelper.<CollectExistGsonBean>observeOnMainThread(this))
                        .subscribe(new BaseSubscriber<CollectExistGsonBean>(){
                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                            }

                            @Override
                            public void onNext(CollectExistGsonBean collectExistGsonBean) {
                                super.onNext(collectExistGsonBean);
                                if (collectExistGsonBean != null
                                        && collectExistGsonBean.getStatus() == Constant.STATUS_SUCCESS
                                        && collectExistGsonBean.getData() != null) {
                                    has_fav = collectExistGsonBean.getData().isHas_fav();
                                    if (has_fav) {
                                        floatBtnCollect.setVisibility(View.GONE);
                                    }else{
                                        floatBtnCollect.setVisibility(View.VISIBLE);
                                    }
                                }
                            }
                        });
            }
        }
    }

    private synchronized void initOfflineData(String data) {
        try {
            offline = data;
            //开启离线模式
            isOffLine = true;
            JSONObject offlineJson = new JSONObject(offline);
            topicObject = offlineJson.getJSONObject("topic");
            novelId = topicObject.getString("id");
            readRecord = mRead_DataBaseUtil.queryHistoryInfo(novelId);
            if (readRecord!=null && TextUtil.isEmpty(sectionId)) {
                sectionId = readRecord.getSection_id();
            }
            catelogArray = offlineJson.getJSONArray("catelog");
            catalogList = new ArrayList<>();
            catalogList.addAll(JSON.parseArray(catelogArray.toString(), NovelSectionListBean.class));
            articlesArray = offlineJson.getJSONArray("articles");
            if (mNovelDetailIds == null) {
                //从文件中获取章节id列表
                mNovelDetailIds = new SparseArray<>();
                if (catelogArray != null) {
                    for (int i = 0; i < catelogArray.length(); i++) {
                        String id = catelogArray.optJSONObject(i).getString("id");
                        mNovelDetailIds.put(i,id);
                        if (i == 0 && TextUtils.isEmpty(sectionId)) {
                            sectionId = id;
                        }
                        if (id.equalsIgnoreCase(sectionId)) {
                            realIdsPos = i;
                            articleItem = realIdsPos ;// 当前页码
                        }
                    }
                }
            }
            if(isPageTurningVertical()){// 判断翻页模式
                novel_left_to_right.setVisibility(View.GONE);
                mNovelViewGroup.setVisibility(View.VISIBLE);
                if (detailsAdapter != null) {
                    detailsAdapter.refush(mNovelDetailIds, articlesArray,topicObject.toString());
                }else if(!isChangeOffline){
                    isFirstPageTurn = true;
                    detailsAdapter = new NovelSectionDetailsAdapter(getSupportFragmentManager(), mNovelDetailIds,topicObject.toString(), novelId);
                    mNovelViewGroup.setAdapter(detailsAdapter);
                    isFirstPageTurn = false;
                    mNovelViewGroup.setCurrentItem(articleItem);
                }else{
                    detailsAdapter = new NovelSectionDetailsAdapter(getSupportFragmentManager(), mNovelDetailIds,topicObject.toString(), novelId);
                    mNovelViewGroup.setAdapter(detailsAdapter);
                    mNovelViewGroup.setCurrentItem(articleItem-1);
                    Log.d(TAG, "initData: " + realIdsPos);//// TODO: 16/10/13 记录上次阅读位置
                }
            }else{
                mNovelViewGroup.setVisibility(View.GONE);
                novel_left_to_right.setVisibility(View.VISIBLE);
                if (sectionDetailsLRFragmentNew == null) {
                    sectionDetailsLRFragmentNew = SectionDetailsLRFragmentNew.newInstanceOffline(sectionId, offline,novelId);
                    FragmentManager fragmentManager = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.add(R.id.novel_left_to_right, sectionDetailsLRFragmentNew);
                    fragmentTransaction.commit();
                }
                sectionDetailsLRFragmentNew.setChaptersList(mNovelDetailIds);

            }
            // 页码
            if (topicBean == null) {
                topicBean = new HomeTopBean();
                topicBean.setJson2(topicObject);
                if (topicBean.getTags() != null && topicBean.getTags().length > 0) {
                    tagsBeans = topicBean.getTags();
                }
                articleItem = realIdsPos + 1;// 当前页码
                articleNum = Integer.valueOf(topicBean.getArticle_num());
                articleTitle = topicBean.getTitle();
                shareTitle = topicBean.getTitle();
                if ((tagsBeans!=null)&&(tagsBeans.length>0))
                {
                    tagStrings=tagsBeans[0].getName();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void enterNovelList() {
        if (topicBean == null) {
            return;
        }
        Intent intent = new Intent(NovelSectionDetailsActivity.this, NovelDesToDetailActivity.class);
        intent.putExtra(NovelDesToDetailActivity.INTENT_OFFLINE_FLAG, isOffLine);
        intent.putExtra(INTENT_KEY_OFFLINE_BOOK_KEY,offlineKey);
        intent.putExtra(NovelDesToDetailActivity.INTENT_CURR_POS, realIdsPos);
        intent.putExtra(NovelDesToDetailActivity.ARTICLEID, topicBean.getId());
        intent.putExtra(NovelDesToDetailActivity.INTENT_IS_ACTIVITY_FOR_RESULT, true);
        startActivityForResult(intent,CATLOG_PAGE_REQUEST);
    }

    public void giveGift(){
        if (topicBean != null){
            if (contentBean != null){
                Map<String,String> map = new HashMap();
                map.put("marticle_id" , contentBean.getId());
                TMAnalysis.event(this , "give_gift_in_novel"  , map);
                boolean isNight = ReadThemeHelper.getReadTheme().getThemeType()==ThemeType.TYPE_NIGHT;
                GiftDialogManager.getInstance(this, topicBean,isNight);
            }
        }
    }

    public void enterNovelComment() {

        if (isYouthModel) {
            Toast.makeText(this,"青少年模式不支持该功能",Toast.LENGTH_LONG).show();
            return;
        }
        if (contentBean == null) {
            return;
        }
        Intent intent = new Intent(NovelSectionDetailsActivity.this, NovelDesToCommActivity.class);
        intent.putExtra(Constant.NOVEL_HOME_BEAN, contentBean);
        intent.putExtra(Constant.TOPIC, contentBean.getTopicId());
        intent.putExtra(Constant.ARTICLE_ID, readID);
        intent.putExtra(Constant.FLOWERSHOWFLAG, Constant.FLOWER_SHOW);
        startActivity(intent);
    }


    public void enter_novel(View view) {
        if (novelId == null || novelId.equals("")) {
            return;
        }
        StartActivityUtil.novelOnclick(NovelSectionDetailsActivity.this, novelId);
    }

    private boolean isOffLine = false;

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        if (dialog != null && dialog.isShowing()) {
            try {
                dialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (response.getStatus() == 0) {
            if(vsNotNetwork.getVisibility() == View.VISIBLE){
                vsNotNetwork.setVisibility(View.GONE);
            }
            try {
                switch (handleType) {
                    // 章节文字数据
//                    case HomeMainServices.HANDLE_TYPE_LOAD_NOVEL_DETAILS:
                    case HomeMainServices.HANDLE_TYPE_LOAD_SECTION_NOVEL:
                        if (response.getStatus() == Constant.STATUS_SUCCESS) {
                            JSONObject jsonObject = (JSONObject) response.getData();
                            if(catalogList == null){
                                catalogList = new ArrayList<>();
                            }
                            // 所有章节id
                            if (mNovelDetailIds == null) {
                                mNovelDetailIds = new SparseArray<>();
                                JSONArray idsArray = jsonObject.getJSONArray("list");
                                //qlx
                                if (sectionId == null){
                                    sectionId = "";
                                }
                                if ( sectionId.length() <= 0 && idsArray != null && idsArray.length() > 0){
                                    sectionId = idsArray.getJSONObject(0).getString("id");
                                }

                                for (int i = 0; i < idsArray.length(); i++)
                                {
                                    NovelSectionListBean catalog = new NovelSectionListBean();
                                    catalog.setId(idsArray.getJSONObject(i).getString("id"));
                                    catalog.setTitle(idsArray.getJSONObject(i).getString("title"));
                                    catalogList.add(catalog);
                                    mNovelDetailIds.put(i,idsArray.getJSONObject(i).getString("id"));
                                    if (idsArray.getJSONObject(i).getString("id").equalsIgnoreCase(sectionId))
                                    {
                                        readID = sectionId;
                                        realIdsPos = i;
                                        articleItem = realIdsPos + 1;// 当前页码
                                        isSectionId = true;
                                    }
                                    if(Long.parseLong(sectionId) >= Long.parseLong(idsArray.getJSONObject(i).getString("id"))){
                                        sectionPosition = i;
                                    }
                                }
                            }
                            setChapterProgress();
                            if(isPageTurningVertical()){// 判断翻页模式
                                detailsAdapter = new NovelSectionDetailsAdapter(getSupportFragmentManager(), mNovelDetailIds, novelId);
                                mNovelViewGroup.setAdapter(detailsAdapter);
                                if(isSectionId){
                                    mNovelViewGroup.setCurrentItem(realIdsPos);
                                }else{
                                    mNovelViewGroup.setCurrentItem(sectionPosition);
                                }
                            }else{
                                if (sectionDetailsLRFragmentNew == null) {
                                    sectionDetailsLRFragmentNew = SectionDetailsLRFragmentNew.newInstance(sectionId, novelId);
                                    FragmentManager fragmentManager = getFragmentManager();
                                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                                    fragmentTransaction.add(R.id.novel_left_to_right, sectionDetailsLRFragmentNew);
                                    fragmentTransaction.commit();
                                }
                                sectionDetailsLRFragmentNew.setChaptersList(mNovelDetailIds);
                            }
                            // 页码
                        } else
                        {
                            //UIUtil.toastMessage(NovelSectionDetailsActivity.this, Constant.loadingFail);
                        }
                        break;
                    case CommentService.HANDLE_PUBLISH_COMMONET:
                        if (response.getStatus() == Constant.STATUS_SUCCESS)
                        {
                            CommentDataBean scrore = new CommentDataBean();
                            scrore.setJson(((JSONObject) response.getData()).getJSONObject("score_result"));
                            int commentScore = Integer.valueOf(scrore.getScore());
                            if (commentScore != 0)
                            {
                                NoRepeatToast.setToast(this, "评论成“攻” +2豆子").show();
                            } else
                            {
                                NoRepeatToast.setToast(this, "评论成“攻”" + Constant.COMMENT_TODAY_FULL).show();
                            }
                            setCommment();
                        } else
                        {
                            NoRepeatToast.setToast(this, DiaobaoUtil.getErrorTips(response)).show();
                        }
                        break;
                    case PersonalInfoService.HANDLE_ADD_COLLECT:
                        isCollect = false;
                        if (response.getStatus() == Constant.STATUS_SUCCESS)
                        {
                            has_fav = true;
                            floatBtnCollect.setVisibility(View.GONE);
                            NotifyUtil.collectStatusChange(novelId,Constant.OBJECT_TYPE_NOVEL,true);
                            UIUtil.toastMessage(NovelSectionDetailsActivity.this, "收藏成功");
                            ivCollect.setImageResource(ReadThemeHelper.getReadTheme().getMoreOperationTheme().getHavImageSelect());
                            tvCollect.setText("已收藏");
                            Constant.isHasFav = has_fav;
                        } else
                        {
                            UIUtil.toastMessage(NovelSectionDetailsActivity.this, Constant.loadingFail);
                        }
                        break;
                    case PersonalInfoService.HANDLE_DEL_COLLECT:
                        isCollect = false;
                        if (response.getStatus() == Constant.STATUS_SUCCESS)
                        {
                            has_fav = false;
                            NotifyUtil.collectStatusChange(novelId,Constant.OBJECT_TYPE_NOVEL,false);
                            UIUtil.toastMessage(NovelSectionDetailsActivity.this, "取消收藏");
                            ivCollect.setImageResource(ReadThemeHelper.getReadTheme().getMoreOperationTheme().getHavImageUnSelect());
                            tvCollect.setText("收藏");
                            Constant.isHasFav = has_fav;
                        } else
                        {
                            UIUtil.toastMessage(NovelSectionDetailsActivity.this, Constant.loadingFail);
                        }
                        break;
                    default:
                        break;
                }
            } catch (Exception e)
            {
                e.printStackTrace();
                if (dialog != null && dialog.isShowing())
                {
                    dialog.dismiss();
                }
            }
        }else {
            NoRepeatToast.setToast(this, DiaobaoUtil.getErrorTips(response)).show();
            if(!isOffLine && !isCollect){
                if(vsNotNetwork.getVisibility() != View.VISIBLE){
                    vsNotNetwork.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void initFirstFragmentData() {
        if (topicBean != null) {
            if (topicBean.getTags() != null && topicBean.getTags().length > 0)
            {
                tagsBeans = topicBean.getTags();
            }
            if (topicBean.getHas_permissions() != null && "1".equals(topicBean.getHas_permissions())){
                giftLayout.setVisibility(View.VISIBLE);
            }else {
                giftLayout.setVisibility(View.GONE);
            }
            novelId = topicBean.getId();
            articleNum = Integer.valueOf(topicBean.getArticle_num());
            articleTitle = topicBean.getTitle();
            shareTitle =  topicBean.getTitle();

            if (tagsBeans != null && tagsBeans.length > 0)
            {
                tagStrings=tagsBeans[0].getName();

                tagStringsArray=new String[tagsBeans.length];
                try{
                    for(int i=0;i<=tagStrings.length();i++){
                        tagStringsArray[i]=tagsBeans[i].getName();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        setCommentCount();
    }

    private void setCommment() {
        String mCount = mChatCount.getText().toString();
        int comm_num = Integer.valueOf(mCount) + 1;
        if (mCount != null && !"".equals(mCount))
        {
            mChatCount.setText(comm_num + "");
        } else
        {
            mChatCount.setText("1");
        }
        for (int i = 0; i < mCommentListNum.size(); i++)
        {
            if (mCommentListNum.get(i).get("article").equalsIgnoreCase(getArticle(realIdsPos)))
            {
                Map<String, String> map = new HashMap<String, String>();
                map.put("article", getArticle(realIdsPos));
                map.put("comment_num", String.valueOf(comm_num));
                mCommentListNum.set(i, map);
                break;
            }
        }
    }

    private TagsBean[] tagsBeans;
    public HomeTopBean topicBean;
    private HomeTopBean contentBean;

    public HomeTopBean getContentBean() {
        return contentBean;
    }

    public void setContentBean(HomeTopBean contentBean) {
        this.contentBean = contentBean;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case ENTER_NOVEL_TO_SWEEP_REQUEST:
                if (resultCode == BACK_TO_NOVEL_DES_RESULT) {
                    finish();
                }
                break;
            case ENTER_SELECT_READ_ANIMATION_REQUEST:
                if (data != null) {
                    int type = data.getIntExtra(IntentKey.INTENT_KEY_TURN_PAGE_ANIMATION, Constant.ReadAnimationType.VerticalScroll);
                    if (type == Constant.ReadAnimationType.HorizontalCover) {
                        turnToHorizontalCover();
                    } else if (type == Constant.ReadAnimationType.VerticalScroll) {
                        turnToVerticalScroll();
                    } else if (type == Constant.ReadAnimationType.NONE) {
                    } else if (type == Constant.ReadAnimationType.LikeBook) {
                    }
                }
                break;
            case CATLOG_PAGE_REQUEST:
                refreshData(data);
                break;
            case ENTER_SELECT_READ_INDENT_REQUEST:
                if (data != null) {
                    int type = data.getIntExtra(IntentKey.INTENT_KEY_READ_INDENT, Constant.ReadIndentType.FORMAT);
                    setIndent(type);
                }
        }
    }


    private boolean isAutoPlayMuneVisiable;
    /**
     * 显示/隐藏 自动播放菜单
     * @param visiable
     */
    public void setAutoPlayMuneVisiable(boolean visiable){
        if (llAutoPlay != null && isAutoPlayMuneVisiable != visiable){
            // 0是底部框，1是顶部框
            ObjectAnimator[] objectAnimators = new ObjectAnimator[1];
            AnimatorSet animatorSet = new AnimatorSet();
            // 出现
            if (visiable) {
                llAutoPlay.setVisibility(View.VISIBLE);
                objectAnimators[0] = ObjectAnimator.ofFloat(llAutoPlay, "translationY", com.taptech.doufu.util.ScreenUtil.getScreenHeight(this), 0);
            }
            // 隐藏
            else {
                objectAnimators[0] = ObjectAnimator.ofFloat(llAutoPlay, "translationY", 0, com.taptech.doufu.util.ScreenUtil.getScreenHeight(this) - mBottomLayout.getMeasuredHeight());
            }
            try{
                animatorSet.setDuration(500);
                animatorSet.playTogether(objectAnimators);
                animatorSet.start();
                isAutoPlayMuneVisiable = visiable;
            }catch (AndroidRuntimeException e){
                e.printStackTrace();
            }
        }
    }

    public boolean isSecondMuneVisiable = true;
    /**
     * 显示/隐藏 二级菜单
     * @param visiable
     */
    public void setSecondMuneVisiable(boolean visiable){
        if (rlSecondLevelMenu != null && isSecondMuneVisiable != visiable){
            // 0是底部框，1是顶部框
            ObjectAnimator[] objectAnimators = new ObjectAnimator[1];
            AnimatorSet animatorSet = new AnimatorSet();
            // 出现
            if (visiable) {
                rlSecondLevelMenu.setVisibility(View.VISIBLE);
                objectAnimators[0] = ObjectAnimator.ofFloat(rlSecondLevelMenu, "translationY", com.taptech.doufu.util.ScreenUtil.getScreenHeight(this), 0);
            }
            // 隐藏
            else {
                objectAnimators[0] = ObjectAnimator.ofFloat(rlSecondLevelMenu, "translationY", 0, com.taptech.doufu.util.ScreenUtil.getScreenHeight(this) - mBottomLayout.getMeasuredHeight());
            }
            try{
                animatorSet.setDuration(500);
                animatorSet.playTogether(objectAnimators);
                animatorSet.start();
                isSecondMuneVisiable = visiable;
            }catch (AndroidRuntimeException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置屏幕常亮
     * @param isUnLock
     */
    private void setScreenUnLock(boolean isUnLock) {
        if (isUnLock) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }else{
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }


    /**
     * 设置行间距
     * @param space
     */
    private void setLineSpace(float space){
        if (detailsAdapter != null && detailsAdapter.getCount() > 0) {
            SectionDetailsFragment sdfOne = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
            sdfOne.setLineSpace(space);
            if (mNovelViewGroup.getCurrentItem() - 1 >= 0) {
                SectionDetailsFragment sdfTwo = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem() - 1);
                sdfTwo.setLineSpace(space);
            }
            if (mNovelViewGroup.getCurrentItem() + 2 < detailsAdapter.getCount()) {
                SectionDetailsFragment sdfThree = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem() + 1);
                sdfThree.setLineSpace(space);
            }
        }
        if (sectionDetailsLRFragmentNew != null ) {
            sectionDetailsLRFragmentNew.setLineSpace(space);
        }
    }


    /**
     * 设置缩进
     * @param type
     */
    private void setIndent(int type) {
        if (detailsAdapter != null && detailsAdapter.getCount() > 0) {
            SectionDetailsFragment sdfOne = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
            sdfOne.setIndent(type);
            if (mNovelViewGroup.getCurrentItem() - 1 >= 0) {
                SectionDetailsFragment sdfTwo = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem() - 1);
                sdfTwo.setIndent(type);
            }
            if (mNovelViewGroup.getCurrentItem() + 2 < detailsAdapter.getCount()) {
                SectionDetailsFragment sdfThree = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem() + 1);
                sdfThree.setIndent(type);
            }
        }
        if (sectionDetailsLRFragmentNew != null) {
            sectionDetailsLRFragmentNew = null;
            if (offline != null) {
                sectionDetailsLRFragmentNew = SectionDetailsLRFragmentNew.newInstanceOffline(sectionId, offline,novelId);
            }else{
                sectionDetailsLRFragmentNew = SectionDetailsLRFragmentNew.newInstance(sectionId, novelId);
            }
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.novel_left_to_right, sectionDetailsLRFragmentNew);
            fragmentTransaction.commit();
            mapContent.clear();
            sectionDetailsLRFragmentNew.setChaptersList(mNovelDetailIds);
        }
    }


    /**
     * 显示一级菜单
     */
    public void showFirstMenu() {
        setSecondMuneVisiable(false);
        setTopAndBottomLayoutVisiable(true);
    }

    /**
     * 显示二级菜单
     */
    public void showSecondMenu() {
        setTopAndBottomLayoutVisiable(false);
        setSecondMuneVisiable(true);
        hideChapterProgress();
    }


    /**
     * 隐藏菜单
     */
    public void hideMenu() {
        setTopAndBottomLayoutVisiable(false);
        setSecondMuneVisiable(false);
        hideChapterProgress();
    }

    /**
     * 显示/隐藏 顶部&底部操作栏
     * @param visiable
     */
    public void setTopAndBottomLayoutVisiable(boolean visiable){
        if (mBottomLayout != null && mTopLayout != null && isTopAndBottomVisiable != visiable){
            // 0是底部框，1是顶部框
            ObjectAnimator[] objectAnimators = new ObjectAnimator[3];
            AnimatorSet animatorSet = new AnimatorSet();
            // 出现
            if (visiable ) {
                objectAnimators[0] = ObjectAnimator.ofFloat(mBottomLayout, "translationY", com.taptech.doufu.util.ScreenUtil.getScreenHeight(this), 0);
                objectAnimators[1] = ObjectAnimator.ofFloat(mTopLayout, "translationY", -mTopLayout.getMeasuredHeight(), 0);
                objectAnimators[2] = ObjectAnimator.ofFloat(floatBtnCollect, "translationX", floatBtnCollect.getMeasuredWidth(), 0);
            }
            // 隐藏
            else {
                objectAnimators[0] = ObjectAnimator.ofFloat(mBottomLayout, "translationY", 0, com.taptech.doufu.util.ScreenUtil.getScreenHeight(this) - mBottomLayout.getMeasuredHeight());
                objectAnimators[1] = ObjectAnimator.ofFloat(mTopLayout, "translationY", 0, -mTopLayout.getMeasuredHeight());
                objectAnimators[2] = ObjectAnimator.ofFloat(floatBtnCollect, "translationX", 0, floatBtnCollect.getMeasuredWidth());
            }
            try{
                animatorSet.setDuration(500);
                animatorSet.playTogether(objectAnimators);
                animatorSet.start();
                isTopAndBottomVisiable = visiable;
            }catch (AndroidRuntimeException e){
                e.printStackTrace();
            }
        }
    }


    public int getRealIdsPos() {
        return realIdsPos;
    }

    private int realIdsPos;// 从服务器的ids数组中取

    public void setReadID(String readID) {
        this.readID = readID;
    }

    private String readID = "";


    @Override
    public void onResume()
    {
        super.onResume();
        startReadTime = System.currentTimeMillis();
        if(isLogin != AccountService.getInstance().isLogin()){
            isLogin = AccountService.getInstance().isLogin();
            getPayInfo();
            setFragmentPayLayout();
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_READ_TIME,novelId,System.currentTimeMillis()-startReadTime);
    }




    /**
     * 登录成功后回到此页面，如果该章节为收费章节，则重新请求数据
     */
    private void setFragmentPayLayout(){
        if(mNovelViewGroup != null && detailsAdapter != null && detailsAdapter.getCount() > 0){
            SectionDetailsFragment fragment = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
            if(fragment != null && !fragment.isPay){
                fragment.toSendRequestData();
            }
            if(mNovelViewGroup.getCurrentItem() - 1 >= 0){
                SectionDetailsFragment sdfTwo = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem()-1);
                if(sdfTwo != null && !sdfTwo.isPay){
                    sdfTwo.toSendRequestData();
                }
            }
            if(mNovelViewGroup.getCurrentItem() + 2 < detailsAdapter.getCount()){
                SectionDetailsFragment sdfThree = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem()+1);
                if(sdfThree != null && !sdfThree.isPay){
                    sdfThree.toSendRequestData();
                }
            }
        }
        if (sectionDetailsLRFragmentNew != null&&!sectionDetailsLRFragmentNew.isPay) {
            sectionDetailsLRFragmentNew.toSendRequestData();
        }
    }

    public void synchorizontaldata(String sectionId) {
        if (sectionDetailsLRFragmentNew != null) {
            sectionDetailsLRFragmentNew.removeCacheForPay(sectionId);
        }
    }


    public void toReloadPreviewAndNextData(){
        if(mNovelViewGroup != null && detailsAdapter != null && detailsAdapter.getCount() > 0){
            if(mNovelViewGroup.getCurrentItem() - 1 >= 0){
                SectionDetailsFragment sdfTwo = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem()-1);
                if(sdfTwo != null && !sdfTwo.isPay){
                    sdfTwo.toSendRequestData();
                }
            }
            if(mNovelViewGroup.getCurrentItem() + 2 < detailsAdapter.getCount()){
                SectionDetailsFragment sdfThree = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem()+1);
                if(sdfThree != null && !sdfThree.isPay){
                    sdfThree.toSendRequestData();
                }
            }
        }
        if (sectionDetailsLRFragmentNew != null) {
            sectionDetailsLRFragmentNew.setCleanCache(true);
            sectionDetailsLRFragmentNew.removeCacheForAntoPay();
        }
    }

    @Override
    protected void onPause() {
        /**
         * 更新阅读历史
         */
        try
        {

            if(realIdsPos <= 0 && articleNum ==0 && TextUtils.isEmpty(articleTitle)){
                super.onPause();
                return;
            }
            if (isPageTurningVertical()) {
                DiaoBaoSharedPreferences.setSharedPreferencesValueToInt("read_vertical_"+novelId,verticalY,this);
            }else{
                if (sectionDetailsLRFragmentNew != null) {
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToString("read_horizontal_"+novelId,sectionDetailsLRFragmentNew.currPage+" "+sectionDetailsLRFragmentNew.currPos,this);
                }
            }
            readRecord = mRead_DataBaseUtil.queryHistoryInfo(novelId);
            if (readRecord != null) {
                if((topicBean!=null)&&(topicBean.getImages()[0]!=null)){
                    mRead_DataBaseUtil.update(novelId, getArticle(realIdsPos), articleItem, articleNum, articleTitle, getTimeBySystem(),topicBean.getImages()[0].getImgUrl(),Constant.OBJECT_TYPE_NOVEL);
                }else{
                    mRead_DataBaseUtil.update(novelId, getArticle(realIdsPos), articleItem, articleNum, articleTitle, getTimeBySystem(),null,Constant.OBJECT_TYPE_NOVEL);
                }
            }else {
                if((topicBean!=null)&&(topicBean.getImages()[0]!=null)){
                    mRead_DataBaseUtil.insert(novelId, getArticle(realIdsPos), articleItem, articleNum, articleTitle, getTimeBySystem(),topicBean.getImages()[0].getImgUrl(),Constant.OBJECT_TYPE_NOVEL);
                }else{
                    mRead_DataBaseUtil.insert(novelId, getArticle(realIdsPos), articleItem, articleNum, articleTitle, getTimeBySystem(), null,Constant.OBJECT_TYPE_NOVEL);
                }
            }
            ReadRecord record = new ReadRecord();
            record.setType(Constant.OBJECT_TYPE_NOVEL);
            record.setSection_id(getArticle(realIdsPos));
            record.setNovel_id(novelId);
            record.setPosition(articleItem>0?articleItem:1);
            record.setAll_num(articleNum);
            record.setTime(getTimeBySystem());
            record.setName(articleTitle);
            if(topicBean!=null && topicBean.getImages()!=null &&
                    topicBean.getImages().length>0 &&(topicBean.getImages()[0]!=null)){
                record.setImg_url(topicBean.getImages()[0].getImgUrl());
            }
            ReadHistoryUtil.addOrUpdateData(record);

            NotifyUtil.refreshCollectCellNotify(novelId,getArticle(realIdsPos),articleItem>0?articleItem:1);

            EventBusNovelReadRecord event = new EventBusNovelReadRecord();
            event.setTag(EventBusNovelReadRecord.Companion.getTag());
            event.setNovelId(novelId);
            event.setSectionId(record.getSection_id());
            event.setPosition(record.getPosition());
            EventBus.getDefault().post(event);

            BaseEventBusBean eventBus = new BaseEventBusBean();
            eventBus.setTag(EventBusConstant.TAG_BOOK_SHELF);
            EventBus.getDefault().post(eventBus);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mobileState != null){
            mobileState.destoryListner();
        }
        offline = null;
        ReadThemeHelper.clearTheme();
        EventBus.getDefault().unregister(this);
        File file = new File(FileUtil.path);
        FileUtil.getInstance().delete(file);

    }


    BottomSheetDialog shareDialog;
    public void topShare(View v) {

//        String desc = "我正在 豆花阅读 App 看《"+topicBean.getTitle()+"》小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! "+topicBean.getShareUrl();
//        ShareUtil.Companion.shareText(this,topicBean.getTitle(),desc);

        if (contentBean == null) {
            return;
        }



        if (shareDialog == null){
            shareDialog = ShareUtils.getBottomDialog(this, false, new ShareUtils.OnClickListener() {
                @Override
                public void onClickItem(int social_type) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("social_type",social_type+"");
                    TMAnalysis.event(NovelSectionDetailsActivity.this, UmengEventName.NOVEL_READER_SHARE_ACTION, map);
                    if (social_type == ShareType.Poster) {
                        NovelPosterActivity.Companion.startActivity(NovelSectionDetailsActivity.this, getNovelDetailBean());
                    } else if (social_type == ShareType.CopyLink) {
                        if (topicBean != null && !TextUtils.isEmpty(topicBean.getShareUrl())) {
                            ShareUtils.copyLike(NovelSectionDetailsActivity.this,topicBean.getShareUrl());
                        }else{
                            String url = Constant.DOWN_URL_WX;
                            if (contentBean!=null && !TextUtil.isEmpty(contentBean.getShareUrl())) {
                                url = contentBean.getShareUrl();
                            }
                            ShareUtils.copyLike(NovelSectionDetailsActivity.this,url);
                        }
                    } else if (social_type == ShareType.Weibo) {
                        ShareBeansInfo info = getShareBean();
                        NovelDetailBean novelDetailBean = getNovelDetailBean();
                        boolean flag = false;
                        if (topicBean != null && topicBean.getTags() != null && topicBean.getTags().length>0) {
                            for (int i = 0; i < topicBean.getTags().length; i++) {
                                if (topicBean.getTags()[i].getName().equals("第六届豆花杯")) {
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if (flag) {
                            info.setShartText("我在@豆花 发现了一本好书《"+novelDetailBean.getTitle()+"》，介绍给你们。#第六届豆花杯##豆花阅读#（"+novelDetailBean.getShareUrl()+"）");
                        }else{
                            info.setShartText("我在@豆花 发现了一本好书《"+novelDetailBean.getTitle()+"》，介绍给你们。#豆花阅读#（"+novelDetailBean.getShareUrl()+"）");
                        }
                        info.setSocial_type(social_type);
                        ShareUtils.thirdPartyShare(NovelSectionDetailsActivity.this,info);
                    }else{
                        ShareBeansInfo info = getShareBean();
                        info.setSocial_type(social_type);
                        ShareUtils.thirdPartyShare(NovelSectionDetailsActivity.this,info);
                    }
                }

                @Override
                public void onClickHelp() {
                    BrowseActivity.startActivity(NovelSectionDetailsActivity.this,"https://api.doufu.la/journal/detail?id=745");
                }
            });
        }
        boolean isNight = ReadThemeHelper.getReadTheme().getThemeType() == ThemeType.TYPE_NIGHT;
        View lay = shareDialog.findViewById(R.id.lay);
        View line = shareDialog.findViewById(R.id.lineBottom);
        if (isNight) {
            lay.setBackgroundResource(R.color.fg_dark);
            line.setBackgroundResource(R.color.sep_dark);
        }else{
            lay.setBackgroundResource(R.color.white);
            line.setBackgroundResource(R.color.divider_line_color_3);
        }
        shareDialog.show();
    }

    private List<TagBean> getTagList() {
        List<TagBean> tagBeanList = new ArrayList<>();
        if (topicBean != null && topicBean.getTags() != null && topicBean.getTags().length>0) {
            for (int i = 0; i < topicBean.getTags().length; i++) {
                TagBean bean = new TagBean();
                bean.setName(topicBean.getTags()[i].getName());
                tagBeanList.add(bean);
            }
        }
        return tagBeanList;
    }

    private NovelDetailBean getNovelDetailBean() {
        NovelDetailBean bean = new NovelDetailBean();
        if (topicBean!=null && !TextUtils.isEmpty(topicBean.getTitle())) {
            bean.setTitle(topicBean.getTitle());
        }
        if (topicBean != null && topicBean.getImages() != null
                && topicBean.getImages().length > 0
                && topicBean.getImages()[0] != null
                && !TextUtils.isEmpty(topicBean.getImages()[0].getImgUrl())) {
            bean.setWith_image_w(topicBean.getImages()[0].getImgUrl());
        }
        if (contentBean != null) {
            bean.setDes(contentBean.getDes());
            bean.setUser(contentBean.getUser());
        }
        if (topicBean != null && !TextUtils.isEmpty(topicBean.getShareUrl())) {
            bean.setShareUrl(topicBean.getShareUrl());

        }else{
            String url = Constant.DOWN_URL_WX;
            if (contentBean!=null && !TextUtil.isEmpty(contentBean.getShareUrl())) {
                url = contentBean.getShareUrl();
            }
            bean.setShareUrl(url);
        }
        bean.setTags(getTagList());

        return bean;
    }

    private ShareBeansInfo getShareBean() {
        ShareBeansInfo shareBean = new ShareBeansInfo();
        shareBean.id = novelId;
        shareBean.dataType = 1;
        if (contentBean != null) {
            shareBean.shareUrl = contentBean.getShareUrl();
            shareBean.setObject_type(contentBean.getObject_type());
        }
        if (topicBean != null && !TextUtils.isEmpty(topicBean.getDes())) {
            shareBean.shartText = topicBean.getDes();
        }
        if (topicBean!=null && !TextUtils.isEmpty(topicBean.getTitle())) {
            shareBean.setTitle(topicBean.getTitle());
        }
        if (topicBean != null && !TextUtils.isEmpty(topicBean.getShareUrl())) {
            shareBean.setShareUrl(topicBean.getShareUrl());
            if (shareBean.getShareData() != null) {
                shareBean.getShareData().setShareUrl(topicBean.getShareUrl());
            }
        }else{
            String url = Constant.DOWN_URL_WX;
            if (!TextUtil.isEmpty(contentBean.getShareUrl())) {
                url = contentBean.getShareUrl();
            }
            shareBean.setShareUrl(url);
            if (shareBean.getShareData() != null) {
                shareBean.getShareData().setShareUrl(url);
            }
        }
        if (topicBean != null && topicBean.getImages() != null
                && topicBean.getImages().length > 0
                && topicBean.getImages()[0] != null
                && !TextUtils.isEmpty(topicBean.getImages()[0].getImgUrl())) {
            shareBean.setImagUrl(topicBean.getImages()[0].getImgUrl());
        }
        return shareBean;
    }

    public void showToTo(){
        showMorePopupWindow();
    }

    public void topMore() {
        showMorePopupWindow();
    }


    /**
     * 初始化更多的窗口
     */
    private void makeMorePopupWindow() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mMoreView = inflater.inflate(R.layout.popup_reader_more_operation, null);
        View lay = mMoreView.findViewById(R.id.lay);
        lay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMorePopupWindow != null) {
                    mMorePopupWindow.dismiss();
                }
            }
        });
        llDialog = (LinearLayout) mMoreView.findViewById(R.id.llDialog);
        LinearLayout mCollect = (LinearLayout) mMoreView.findViewById(R.id.popup_reader_more_collect);
        mCollect.setOnClickListener(morePopopOnclick);
        ivCollect = (ImageView) mMoreView.findViewById(R.id.popup_reader_more_iv_collect);
        tvCollect = (TextView) mMoreView.findViewById(R.id.popup_reader_more_tv_collect);
        popup_reader_more_collect_line = mMoreView.findViewById(R.id.popup_reader_more_collect_line);
        popup_reader_more_collect_line.setVisibility(View.VISIBLE);

        LinearLayout mReport = (LinearLayout) mMoreView.findViewById(R.id.popup_reader_more_report);
        mReport.setOnClickListener(morePopopOnclick);
        mReport.setVisibility(View.VISIBLE);
        ivReport = (ImageView) mMoreView.findViewById(R.id.ivReport);
        tvReport = (TextView) mMoreView.findViewById(R.id.popup_more_report_tv);

        // 分享
        LinearLayout mShare = (LinearLayout) mMoreView.findViewById(R.id.popup_reader_more_share);
        mShare.setVisibility(View.VISIBLE);
        mShare.setOnClickListener(morePopopOnclick);
        ivShare = (ImageView) mMoreView.findViewById(R.id.iv_reader_toolbar_top_share);
        tvShare = (TextView) mMoreView.findViewById(R.id.tv_popup_more_share);
        popup_reader_more_share_line = mMoreView.findViewById(R.id.popup_reader_more_share_line);
        popup_reader_more_share_line.setVisibility(View.VISIBLE);

        LinearLayout mDetail = (LinearLayout) mMoreView.findViewById(R.id.popup_reader_more_detail);
        mDetail.setVisibility(View.VISIBLE);
        mDetail.setOnClickListener(morePopopOnclick);
        ivDetail = (ImageView) mMoreView.findViewById(R.id.iv_reader_toolbar_top_detail);
        tvDetail = (TextView) mMoreView.findViewById(R.id.tv_popup_more_detail);
        popup_reader_more_detail_line = mMoreView.findViewById(R.id.popup_reader_more_detail_line);
        popup_reader_more_detail_line.setVisibility(View.VISIBLE);

        mMorePopupWindow = new PopupWindow(mMoreView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        mMorePopupWindow.setAnimationStyle(R.style.Animation_Right_Left);
        mMorePopupWindow.setBackgroundDrawable(new BitmapDrawable());
    }


    private void showMorePopupWindow() {
        if (mMorePopupWindow == null || contentBean == null) {
            return;
        }
        if (has_fav) {
            ivCollect.setImageResource(ReadThemeHelper.getReadTheme().getMoreOperationTheme().getHavImageSelect());
            tvCollect.setText("已收藏");
        } else {
            ivCollect.setImageResource(ReadThemeHelper.getReadTheme().getMoreOperationTheme().getHavImageUnSelect());
            tvCollect.setText("收藏");
        }
        mMorePopupWindow.showAtLocation(getWindow().getDecorView(), Gravity.TOP | Gravity.RIGHT, ScreenUtil2.dip2px(10), 0);
        mMorePopupWindow.setFocusable(true);
        mMorePopupWindow.setOutsideTouchable(true);
        mMorePopupWindow.update();
    }



    /**
     * 修改字体大小
     * @param fontSize 字体大小
     */
    private void updateTextSize(int fontSize){
        if (detailsAdapter != null && detailsAdapter.getCount() > 0) {
            SectionDetailsFragment sdfOne = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
            sdfOne.updateFontSizeSelection(fontSize);
            if (mNovelViewGroup.getCurrentItem() - 1 >= 0) {
                SectionDetailsFragment sdfTwo = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem() - 1);
                sdfTwo.updateFontSizeSelection(fontSize);
            }
            if (mNovelViewGroup.getCurrentItem() + 2 < detailsAdapter.getCount()) {
                SectionDetailsFragment sdfThree = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem() + 1);
                sdfThree.updateFontSizeSelection(fontSize);
            }
        }
        if (sectionDetailsLRFragmentNew != null ) {
            sectionDetailsLRFragmentNew.setFontSize(fontSize);
        }
    }


    private void handlerCollect() {
        if (AccountService.getInstance().isLogin()) {
            isCollect = true;
            String eventName;
            if (has_fav) {
                dialog.show();
                eventName = UserLogManager.LOG_EVENT_NAME_NOVEL_UN_COLLECT;
                PersonalInfoService.getInstance().delCollectes(novelId, NovelSectionDetailsActivity.this);
            } else {
                eventName = UserLogManager.LOG_EVENT_NAME_NOVEL_COLLECT;
                dialog.show();
                PersonalInfoService.getInstance().addCollectes(novelId, NovelSectionDetailsActivity.this);
            }
            UserLogManager.addLog(eventName,novelId);
        } else {
            AccountService.getInstance().jumpToLogin();
        }
    }


    private String getArticle(int index) {
        if (mNovelDetailIds != null && index >= 0 && index < mNovelDetailIds.size())
        {
            readID = mNovelDetailIds.get(index);
            return mNovelDetailIds.get(index);
        }
        return "";
    }

    private OnClickListener morePopopOnclick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mMorePopupWindow != null && mMorePopupWindow.isShowing()) {
                mMorePopupWindow.dismiss();
            }
            switch (v.getId()) {
                case R.id.popup_reader_more_collect:
                    if (has_fav) {
                        TMAnalysis.event(NovelSectionDetailsActivity.this, UmengEventName.READER_MORE_CANCEL_COLLECT);
                    }else{
                        TMAnalysis.event(NovelSectionDetailsActivity.this, UmengEventName.READER_MORE_COLLECT);
                    }
                    handlerCollect();
                    break;
                case R.id.popup_reader_more_report:
                    TMAnalysis.event(NovelSectionDetailsActivity.this, UmengEventName.READER_MORE_REPORT);
                    if (contentBean != null)
                    {
                        UserBean userBean = contentBean.getUser();
                        if (userBean != null)
                        {
                            HomeMainServices.getInstance().reportContentRequest(NovelSectionDetailsActivity.this, userBean.getUserId(), contentBean.getObject_type(), readID);
                        }
                    }
                    break;
                case R.id.popup_reader_more_share:
                    TMAnalysis.event(NovelSectionDetailsActivity.this, UmengEventName.READER_MORE_SHARE);
                    topShare(v);
                    break;
                case R.id.popup_reader_more_detail:
                    TMAnalysis.event(NovelSectionDetailsActivity.this, UmengEventName.READER_MORE_NOVEL_DETAIL);
                    enter_novel(v);
                    break;
                default:
                    break;
            }
        }
    };

    private void setReadTheme(ReadTheme readTheme) {
        //设置背景
        llAutoPlay.setBackgroundColor(getResources().getColor(readTheme.getMenuBgColor()));
        mTopLayout.setBackgroundColor(getResources().getColor(readTheme.getMenuBgColor()));
        layContent.setBackgroundColor(getResources().getColor(readTheme.getMenuBgColor()));
        mNovelViewGroup.setBackgroundResource(readTheme.getContentBg());
        eyesView.setBackgroundColor(getResources().getColor(readTheme.getEyesViewColor()));
        mBottomLayout.setBackgroundColor(getResources().getColor(readTheme.getMenuBgColor()));
        rlSecondLevelMenu.setBackgroundColor(getResources().getColor(readTheme.getMenuBgColor()));
        llDialog.setBackgroundResource(readTheme.getMoreOperationTheme().getBgImage());
        //设置图标
        mPopMore.setImageResource(readTheme.getTopMenuTheme().getMoreOperationImage());
        ivBack.setImageResource(readTheme.getTopMenuTheme().getBackImage());
        ivOffLine.setImageResource(readTheme.getTopMenuTheme().getDowmloadImage());
        ivGift.setImageResource(readTheme.getTopMenuTheme().getGiftImage());
        ivCollect.setImageResource(readTheme.getMoreOperationTheme().getHavImageUnSelect());
        ivShare.setImageResource(readTheme.getMoreOperationTheme().getShareImage());
        ivReport.setImageResource(readTheme.getMoreOperationTheme().getReportImage());
        ivDetail.setImageResource(readTheme.getMoreOperationTheme().getNovelInfo());
        ivLightSub.setImageResource(readTheme.getSecondMenuTheme().getLowLightImage());
        ivLightAdd.setImageResource(readTheme.getSecondMenuTheme().getHighLightImage());
        ivFontSizeSub.setImageResource(readTheme.getSecondMenuTheme().getSubFontSizeImage());
        ivFontSizeAdd.setImageResource(readTheme.getSecondMenuTheme().getAddFontSizeImage());
        ivFlip.setImageResource(readTheme.getSecondMenuTheme().getChangePageImage());
        ivPlay.setImageResource(readTheme.getSecondMenuTheme().getAutoReadImage());
        ivReadMore.setImageResource(readTheme.getSecondMenuTheme().getMoreReadSetImage());
        ivPre.setImageResource(readTheme.getBottomMenuTheme().getPreImage());
        ivNext.setImageResource(readTheme.getBottomMenuTheme().getNextImage());
        ivCatalog.setImageResource(readTheme.getBottomMenuTheme().getCatalogImage());
        ivNight.setImageResource(readTheme.getBottomMenuTheme().getNightImage());
        ivSet.setImageResource(readTheme.getBottomMenuTheme().getSetImage());
        ivComment.setImageResource(readTheme.getBottomMenuTheme().getCommentImage());
        //设置描述文字颜色
        tvFlip.setTextColor(getResources().getColor(readTheme.getSecondMenuTheme().getFontColor()));
        tvPlay.setTextColor(getResources().getColor(readTheme.getSecondMenuTheme().getFontColor()));
        tvReadMore.setTextColor(getResources().getColor(readTheme.getSecondMenuTheme().getFontColor()));
        tvCatalog.setTextColor(getResources().getColor(readTheme.getBottomMenuTheme().getFontColor()));
        tvNight.setTextColor(getResources().getColor(readTheme.getBottomMenuTheme().getFontColor()));
        tvSet.setTextColor(getResources().getColor(readTheme.getBottomMenuTheme().getFontColor()));
        tvComment.setTextColor(getResources().getColor(readTheme.getBottomMenuTheme().getFontColor()));
        tvCollect.setTextColor(getResources().getColor(readTheme.getMoreOperationTheme().getFontColor()));
        tvShare.setTextColor(getResources().getColor(readTheme.getMoreOperationTheme().getFontColor()));
        tvReport.setTextColor(getResources().getColor(readTheme.getMoreOperationTheme().getFontColor()));
        tvDetail.setTextColor(getResources().getColor(readTheme.getMoreOperationTheme().getFontColor()));
        commentCount.setBackgroundResource(readTheme.getBottomMenuTheme().getCommentRedDotBg());
        commentCount.setTextColor(getResources().getColor(readTheme.getBottomMenuTheme().getCommentRedDotFontColor()));
        tvPlaySpeedSub.setTextColor(getResources().getColor(readTheme.getAutoPlayTheme().getTitleFontColor()));
        tvPlaySpeedAdd.setTextColor(getResources().getColor(readTheme.getAutoPlayTheme().getTitleFontColor()));
        tvExitPlay.setTextColor(getResources().getColor(readTheme.getAutoPlayTheme().getNomalFontColor()));
        llSysLight.setBackgroundResource(readTheme.getSecondMenuTheme().getSysLightBg());
        if (isSysLight) {
            tvSysLight.setTextColor(getResources().getColor(readTheme.getSecondMenuTheme().getSysLightFCSelect()));
        }else{
            tvSysLight.setTextColor(getResources().getColor(readTheme.getSecondMenuTheme().getSysLightFCUnSelect()));
        }
        //设置分割线颜色
        popup_reader_more_collect_line.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        popup_reader_more_detail_line.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        popup_reader_more_share_line.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        mTopLine.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        lineOne.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        lineTwo.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        lineThree.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        playLineOne.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        playLineTwo.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        playLineThree.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));
        playLineFour.setBackgroundColor(getResources().getColor(readTheme.getLineColor()));

        seekbarPlay.setProgressDrawable(getResources().getDrawable(readTheme.getSeekBarProgressColor()));
        seekbarFontSize.setProgressDrawable(getResources().getDrawable(readTheme.getSeekBarProgressColor()));
        seekbarLight.setProgressDrawable(getResources().getDrawable(readTheme.getSeekBarProgressColor()));
        seekbarChapter.setProgressDrawable(getResources().getDrawable(readTheme.getSeekBarProgressColor()));
        seekbarPlay.setThumb(getResources().getDrawable(readTheme.getSeekBarImage()));
        seekbarFontSize.setThumb(getResources().getDrawable(readTheme.getSeekBarImage()));
        seekbarLight.setThumb(getResources().getDrawable(readTheme.getSeekBarImage()));
        seekbarChapter.setThumb(getResources().getDrawable(readTheme.getSeekBarImage()));
        seekbarPlay.setThumbOffset(ScreenUtil2.dip2px(10));
        seekbarFontSize.setThumbOffset(ScreenUtil2.dip2px(10));
        seekbarLight.setThumbOffset(ScreenUtil2.dip2px(10));
        seekbarChapter.setThumbOffset(ScreenUtil2.dip2px(10));
        recycleView.setAlpha(readTheme.getSecondMenuTheme().getThemeListAlpha());
        int autoPlayType = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_AUTO_READ_TYPE, this, Constant.ReadAutoPlayType.LINE);
        if (autoPlayType == Constant.ReadAutoPlayType.LINE) {
            tvPlayLine.setTextColor(getResources().getColor(readTheme.getAutoPlayTheme().getSelectFontColor()));
            tvPlayPage.setTextColor(getResources().getColor(readTheme.getAutoPlayTheme().getUnSelectFontColor()));
        }else{
            tvPlayPage.setTextColor(getResources().getColor(readTheme.getAutoPlayTheme().getSelectFontColor()));
            tvPlayLine.setTextColor(getResources().getColor(readTheme.getAutoPlayTheme().getUnSelectFontColor()));
        }
        if (readTheme.getThemeType() == ThemeType.TYPE_NIGHT) {
            setHalfTransparent();
            tvNight.setText("日间");
        }else{
            setStatusBarFullTransparent();
            tvNight.setText("夜间");
        }
        toSetTheme(readTheme);
        if (adapter != null) {
            adapter.updata(readTheme);
        }
        setProtectEyesView();
    }



    private void toSetTheme(ReadTheme readTheme){// 设置章节内容日夜模式
        try {
            if(detailsAdapter != null && detailsAdapter.getCount() > 0){
                SectionDetailsFragment sdfOne = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
                sdfOne.setReadTheme(readTheme);
                sdfOne.setMobileState(mobileState);
                if(mNovelViewGroup.getCurrentItem() - 1 >= 0){
                    SectionDetailsFragment sdfTwo = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem()-1);
                    sdfTwo.setReadTheme(readTheme);
                    sdfTwo.setMobileState(mobileState);
                }
                if(mNovelViewGroup.getCurrentItem() + 2 < detailsAdapter.getCount()){
                    SectionDetailsFragment sdfThree = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem()+1);
                    sdfThree.setReadTheme(readTheme);
                    sdfThree.setMobileState(mobileState);
                }
            }
            if (sectionDetailsLRFragmentNew != null) {
                sectionDetailsLRFragmentNew.setReadTheme(readTheme);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void topBack() {
        setResult(777, getIntent());
        finish();
    }

    private String getTimeBySystem() {
        String dateStr = dateFormat.format(new Date());// 可以将时间保存起来
        return dateStr;
    }

    public void setCommentCount() {
        commentCount.setVisibility(View.GONE);
        if (contentBean != null && contentBean.getActionMsg() != null)
        {
            String commnent_time = contentBean.getActionMsg().getComment_times();
            if (commnent_time != null && !"".equals(commnent_time) && !"0".equals(commnent_time))
            {
                commentCount.setVisibility(View.VISIBLE);
                commentCount.setText(commnent_time);
            }
        }
    }

    /**
     * 翻页模式是否为上下翻页
     * @return
     */
    private boolean isPageTurningVertical(){//show 横屏 read
        int type = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_READ_ANIMATION,
                this, Constant.ReadAnimationType.VerticalScroll);
        if(type == Constant.ReadAnimationType.VerticalScroll){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }


    @Override
    public void onPageSelected(int position) {
        if(isPageTurningVertical()){
            if(!isClickNextOrPreview ||detailsAdapter != null && position+1 == detailsAdapter.getCount()){// 正常翻页导航栏回弹，点击翻页导航栏不回弹。。。到最后一页时也回弹
                if (isHintShow) {
                    showFirstMenu();
                }else if(isChapterProgressShow){
                    showFirstMenu();
                } else {
                    hideMenu();
                }
            }
            initFirstFragmentData();
            isClickNextOrPreview = false;
            if(detailsAdapter != null && position+1 != detailsAdapter.getCount()){
                SectionDetailsFragment fragment = (SectionDetailsFragment) detailsAdapter.getItem(position);
                realIdsPos = fragment.getRealIdsPos();
                setChapterProgress();
                articleTitle = fragment.getArticleTitle();
                contentBean = fragment.getContentBean();
                if (fragment.getTopicBean() != null) {
                    topicBean = fragment.getTopicBean();
                }
                sectionId = fragment.getSectionId();
                if(!isFirstPageTurn){
                    articleItem = fragment.getArticleItem();
                }
                if (contentBean !=null && contentBean.isNeed_pay()) {
                    if (isShowTicketDialog()){
                        showReadTicketDialog();
                    }
                }
                readID = sectionId;
                fragment.setMobileState(mobileState);
                fragment.toReadInsert();
                fragment.showTip();

                if (!TextUtils.isEmpty(readID)) {
                    readArticleNum+=1;
                    if (isFromCatalog || (mNovelDetailIds != null && mNovelDetailIds.size() > 0 &&
                            readID.equals(mNovelDetailIds.get(mNovelDetailIds.size() - 1)))) {
                        //如果是从目录进入 或者 最后一章则不跳转到上次的记录
                        isFromCatalog = false;
                        DiaoBaoSharedPreferences.setSharedPreferencesValueToInt("read_vertical_"+novelId,0,this);
                    }else{
                        int nowY = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt("read_vertical_" + novelId, this, 0);
                        verticalY = nowY;
                        if (nowY > 0) {
                            fragment.setNowY(nowY);
                            DiaoBaoSharedPreferences.setSharedPreferencesValueToInt("read_vertical_"+novelId,0,this);
                        }
                    }
                }


                if(contentBean != null){
                    setCommentCount();
                }
                if(position == 0){
                    initFirstFragmentData();
                }
                initFirstFragmentData();
            }
            if(detailsAdapter != null && position+1 == detailsAdapter.getCount()){
                hideMenu();
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public void toGetCommentData(int position){
        if(mNovelViewGroup.getCurrentItem() == position){
            onPageSelected(position);
        }
    }


    private void changeFontSizeSeekBar(boolean isAdd) {
        if (seekbarFontSize != null) {
            if (isAdd) {
                if (seekbarFontSize.getMax() > seekbarFontSize.getProgress()) {
                    seekbarFontSize.setProgress(seekbarFontSize.getProgress()+1);
                }
            }else {
                if (seekbarFontSize.getProgress()>0) {
                    seekbarFontSize.setProgress(seekbarFontSize.getProgress()-1);
                }
            }
            updateTextSize(progressToFontSize(seekbarFontSize.getProgress()));
            DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_FONT_SIZE_STATE,
                    seekbarFontSize.getProgress(),getThisActivity());
        }
    }

    private boolean isSysLight = true;
    private boolean isAutoPlay = false;
    private boolean isAutoPlayLine = true;
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()){
            case R.id.floatBtnCollect:
                TMAnalysis.event(this, UmengEventName.READER_COLLECT_FLOAT_BTN);
                handlerCollect();
                break;
            case R.id.llSysLight:
                isSysLight = !isSysLight;
                if (isSysLight) {
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_SYS_LIGHT,true,this);
                    tvSysLight.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getSecondMenuTheme().getSysLightFCSelect()));
                    ScreenBrightnessUtil.setBrightness(this,-1);
                }else{
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_SYS_LIGHT,false,this);
                    tvSysLight.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getSecondMenuTheme().getSysLightFCUnSelect()));
                    int light = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_LIGHT_STATE, this, 10);
                    seekbarLight.setProgress(light);
                    ScreenBrightnessUtil.setBrightness(this,light);
                }
                break;
            case R.id.llSpeedAdd:
                if (seekbarPlay != null && seekbarPlay.getProgress()<seekbarPlay.getMax()) {
                    seekbarPlay.setProgress(seekbarPlay.getProgress()+1);
                }
                break;
            case R.id.llSpeedSub:
                if (seekbarPlay != null && seekbarPlay.getProgress()>0) {
                    seekbarPlay.setProgress(seekbarPlay.getProgress()-1);
                }
                break;
            case R.id.tvPlayPage:
                if (!isAutoPlayLine)
                    return;
                if (sectionDetailsLRFragmentNew != null) {
                    isAutoPlayLine = false;
                    setAutoPlayMuneVisiable(false);
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_AUTO_READ_TYPE,
                            Constant.ReadAutoPlayType.PAGE,this);
                    tvPlayPage.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getAutoPlayTheme().getSelectFontColor()));
                    tvPlayLine.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getAutoPlayTheme().getUnSelectFontColor()));
                    sectionDetailsLRFragmentNew.changePlayType(isAutoPlayLine);
                }
                break;
            case R.id.tvPlayLine:
                if (isAutoPlayLine)
                    return;
                if (sectionDetailsLRFragmentNew != null) {
                    isAutoPlayLine = true;
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_AUTO_READ_TYPE,
                            Constant.ReadAutoPlayType.LINE,this);
                    setAutoPlayMuneVisiable(false);
                    tvPlayLine.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getAutoPlayTheme().getSelectFontColor()));
                    tvPlayPage.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getAutoPlayTheme().getUnSelectFontColor()));
                    sectionDetailsLRFragmentNew.changePlayType(isAutoPlayLine);
                }
                break;
            case R.id.llExitPlay:
                setAutoPlay();
                break;
            case R.id.llFontSizeSub:
                changeFontSizeSeekBar(false);
                break;
            case R.id.llFontSizeAdd:
                changeFontSizeSeekBar(true);
                break;
            case R.id.llReadAnimation:
                intent.setClass(NovelSectionDetailsActivity.this, ReadAnimationActivity.class);
                startActivityForResult(intent,ENTER_SELECT_READ_ANIMATION_REQUEST);
                break;
            case R.id.llReadMoreSet:
                intent.setClass(NovelSectionDetailsActivity.this, ReadMoreSetActivity.class);
                startActivityForResult(intent,ENTER_SELECT_READ_INDENT_REQUEST);
                break;
            case R.id.llPlay:
                if (isPageTurningVertical()) {
                    turnToHorizontalCover();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(500);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        starAutoPlay();
                                    }
                                });
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }else{
                    starAutoPlay();
                }
                break;
            case R.id.llEyes:
                isProtectEyes = !isProtectEyes;
                setProtectEyesView();
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_PAGE_READ_PROTECT_EYES,
                        isProtectEyes,NovelSectionDetailsActivity.this);
                break;
            case R.id.llLightSub:  //降低亮度
                if (seekbarLight == null) {
                    return;
                }
                int progress1 = seekbarLight.getProgress();
                if (progress1 > 0) {
                    progress1--;
                }
                seekbarLight.setProgress(progress1);
                isSysLight = false;
                tvSysLight.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getSecondMenuTheme().getSysLightFCUnSelect()));
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_SYS_LIGHT, false, NovelSectionDetailsActivity.this);

                break;
            case R.id.llLightAdd:  //增强亮度
                if (seekbarLight == null) {
                    return;
                }
                int progress = seekbarLight.getProgress();
                if (progress < 255) {
                    progress++;
                }
                seekbarLight.setProgress(progress);
                isSysLight = false;
                tvSysLight.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getSecondMenuTheme().getSysLightFCUnSelect()));
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_SYS_LIGHT, false, NovelSectionDetailsActivity.this);
                break;
            case R.id.giftLayout:  //送礼
                if (isYouthModel) {
                    Toast.makeText(this,"青少年模式不支持该功能",Toast.LENGTH_LONG).show();
                    return;
                }
                giveGift();
                hideChapterProgress();
                break;
            case R.id.llOther:  //更多操作
                if (isYouthModel) {
                    Toast.makeText(this,"青少年模式不支持该功能",Toast.LENGTH_LONG).show();
                    return;
                }
                topMore();
                hideChapterProgress();
                break;
            case R.id.ivBack: //返回
                topBack();
                break;
            case R.id.llPreView:  //上一章
                preview();
                hideChapterProgress();
                break;
            case R.id.llNextView: //下一章
                nextview();
                hideChapterProgress();
                break;
            case R.id.llCatalog: //目录
                hideChapterProgress();
                enterNovelList();
                break;
            case R.id.llDayAndNight: //夜间模式
                int type;

                if (ReadThemeHelper.getReadTheme().getThemeType() == ThemeType.TYPE_NIGHT) {
                    setStatusBarFullTransparent();
                    type = ThemeType.TYPE_DAY;
                }else{
                    setHalfTransparent();
                    type = ThemeType.TYPE_NIGHT;
                }
                starAnimation(type);
//                setReadTheme(EditNovelThemeHelper.updataReadTheme(type));
                break;
            case R.id.llReadSet: //阅读设置
                showSecondMenu();
                break;
            case R.id.llNovelComment: //评论
                hideChapterProgress();
                enterNovelComment();
                break;
            case R.id.rlRealOffLine:  //离线
                if (isYouthModel) {
                    Toast.makeText(this,"青少年模式不支持该功能",Toast.LENGTH_LONG).show();
                    return;
                }
                if (AccountService.getInstance().isLogin()){
                    String url =  "TFNovel/TFOffLine.js?present=1&read=true&id=" +novelId;
                    presentWeexView(url);
                }else {
                    AccountService.getInstance().jumpToLogin();
                }
                break;
            case R.id.btn_common_novel_no_network:
                if(dialog == null){
                    dialog = new WaitDialog(this, R.style.waitDialog, "");
                    dialog.setCanceledOnTouchOutside(false);
                }
                dialog.show();
                HomeMainServices.getInstance().loadNovelSectionListNew(this, novelId, null);
                break;
            case R.id.rl_novel_section_details_test_hint:
                dismissHint();
                break;
            default:
                break;
        }
    }

    private void starAutoPlay() {
        if (sectionDetailsLRFragmentNew == null) {
            return;
        }
        int autoReadType = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_AUTO_READ_TYPE, this,
                Constant.ReadAutoPlayType.LINE);
        isAutoPlayLine = autoReadType == Constant.ReadAutoPlayType.LINE;
        sectionDetailsLRFragmentNew.setPlayType(isAutoPlayLine);
        setAutoPlay();
    }


    /**
     * 切换为左右覆盖动画
     */
    private void turnToHorizontalCover() {
        setTopAndBottomLayoutVisiable(false);
        mNovelViewGroup.setVisibility(View.GONE);
        novel_left_to_right.setVisibility(View.VISIBLE);
        if (sectionDetailsLRFragmentNew == null) {
            if (offline != null) {
                sectionDetailsLRFragmentNew = SectionDetailsLRFragmentNew.newInstanceOffline(sectionId, offline,novelId);
            }else{
                sectionDetailsLRFragmentNew = SectionDetailsLRFragmentNew.newInstance(sectionId, novelId);
            }
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.novel_left_to_right, sectionDetailsLRFragmentNew);
            fragmentTransaction.commit();
            mapContent.clear();
            sectionDetailsLRFragmentNew.setChaptersList(mNovelDetailIds);
        } else {
            sectionDetailsLRFragmentNew.jumpToCapterNoLock(articleItem);
        }
        DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_READ_ANIMATION,
                Constant.ReadAnimationType.HorizontalCover,this);
        verticalY = 0;
        DiaoBaoSharedPreferences.setSharedPreferencesValueToInt("read_vertical_"+novelId,verticalY,this);
    }
    /**
     * 切换为上下滚动动画
     */
    private void turnToVerticalScroll() {
        setTopAndBottomLayoutVisiable(false);
        if(detailsAdapter == null){
            isFirstPageTurn = true;
            novel_left_to_right.setVisibility(View.GONE);
            mNovelViewGroup.setVisibility(View.VISIBLE);
            if (offline != null) {
                detailsAdapter = new NovelSectionDetailsAdapter(getSupportFragmentManager(), mNovelDetailIds,topicObject.toString(), novelId);
            }else{
                detailsAdapter = new NovelSectionDetailsAdapter(getSupportFragmentManager(), mNovelDetailIds, novelId);
            }
            mNovelViewGroup.setAdapter(detailsAdapter);
            isFirstPageTurn = false;
            mNovelViewGroup.setCurrentItem(articleItem - 1);
        }else{
            novel_left_to_right.setVisibility(View.GONE);
            mNovelViewGroup.setVisibility(View.VISIBLE);
            mNovelViewGroup.setCurrentItem(articleItem - 1);
        }
        DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_READ_ANIMATION,
                Constant.ReadAnimationType.VerticalScroll,this);
        if (sectionDetailsLRFragmentNew != null) {
            DiaoBaoSharedPreferences.setSharedPreferencesValueToString("read_horizontal_"+novelId,"",this);
        }

    }

    public void showHint(){
        //"hint_show"
        SharedPreferences sharedPreferences = getSharedPreferences("hint_show_tip", Activity.MODE_PRIVATE);
        //"is_novel_section_hint"
        if(sharedPreferences.getBoolean("is_novel_section_hint_tip", true)){
            isHintShow = true;
            showFirstMenu();
            rlHint.setVisibility(View.VISIBLE);
        }else{
            isHintShow = false;
            if(rlHint.getVisibility() != View.GONE){
                rlHint.setVisibility(View.GONE);
            }
        }
    }

    private void dismissHint() {
        SharedPreferences mySharedPreferences = getSharedPreferences("hint_show_tip", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.putBoolean("is_novel_section_hint_tip", false);
        editor.commit();
        isHintShow = false;
        rlHint.setVisibility(View.GONE);
        hideMenu();
    }

    public void showBuyTipDialog() {
        String tip ="1、“购买完本”为一次性购买整部作品，不受会员或历史购买影响，统一价格。\n" +
                "2、“当前所有未付费章节原价（会员八折）”低于完本价时，您将不会见到完本购买入口，以避免错失优惠。";
        if (payInfoBean != null && !TextUtils.isEmpty(payInfoBean.getFullBuyNote())) {
            tip = payInfoBean.getFullBuyNote();
        }
        TipSingleBtnDialog dialog = new TipSingleBtnDialog(this,R.style.updateDialog, tip);
        dialog.show();
    }

    /**
     * 上一章
     */
    public void preview(){
        if (UIUtil.isFastClick()) {
            return;
        }
        try {
            if(isPageTurningVertical()){
                if(detailsAdapter != null && detailsAdapter.getCount() > 0 && mNovelViewGroup.getCurrentItem() - 1 >= 0){
                    isClickNextOrPreview = true;
                    isClickNOrPScroll = true;
                    mNovelViewGroup.setCurrentItem(mNovelViewGroup.getCurrentItem() - 1, true);
                }else{
                    UIUtil.toastMessage(this, "已经是第一章了");
                }
            }else{
                if (sectionDetailsLRFragmentNew != null) {
                    sectionDetailsLRFragmentNew.jumpToCapter(articleItem-1);
                }
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下一章
     */
    public void nextview(){
        if (UIUtil.isFastClick()) {
            return;
        }
        try {
            if(isPageTurningVertical()){
                if(detailsAdapter != null && detailsAdapter.getCount() > 0 && mNovelViewGroup.getCurrentItem() + 1 < detailsAdapter.getCount()){
                    isClickNextOrPreview = true;
                    isClickNOrPScroll = true;
                    mNovelViewGroup.setCurrentItem(mNovelViewGroup.getCurrentItem() + 1, true);
                }else{
                    UIUtil.toastMessage(this, "已经是最后一章了");
                }
            }else{
                if (sectionDetailsLRFragmentNew != null) {
                    sectionDetailsLRFragmentNew.jumpToCapter(articleItem+1);
                }
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClickItem(Integer themeType) {
        if (ReadThemeHelper.getReadTheme().getThemeType() == themeType) {
            return;
        }
        setReadTheme(ReadThemeHelper.updataReadTheme(themeType));
    }

    public static void setAnimationTextColor(final TextView textView, int starColor, int endColor) throws NoSuchMethodError {
        ValueAnimator valueAnimator = ValueAnimator.ofArgb(starColor, endColor);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int color = (int) animation.getAnimatedValue();
                if (textView != null) {
                    textView.setTextColor(color);
                }
            }
        });
        valueAnimator.setRepeatCount(0);
        valueAnimator.setDuration(1000);
        valueAnimator.start();
    }

    public static void setAnimationColor(final View view, int starColor, int endColor,long time)throws NoSuchMethodError  {
        ValueAnimator valueAnimator = ValueAnimator.ofArgb(starColor, endColor);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int color = (int) animation.getAnimatedValue();
                if (view != null) {
                    view.setBackgroundColor(color);
                }
            }
        });
        valueAnimator.setRepeatCount(0);
        valueAnimator.setDuration(time);
        valueAnimator.start();
    }


    public static void setAnimationAlpha(final View view,float start,float end,long time)throws NoSuchMethodError  {
        try {
            ValueAnimator valueAnimator = ValueAnimator.ofFloat(start, end);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float alpha = (float) animation.getAnimatedValue();
                    if (view != null) {
                        view.setAlpha(alpha);
                    }
                }
            });
            valueAnimator.setRepeatCount(0);
            valueAnimator.setDuration(time);
            valueAnimator.start();
        } catch (NoSuchMethodError e) {

        }
    }

    private boolean canClick = true;
    private void starAnimation(int themeType) {
        if (!canClick) {
            return;
        }
        canClick = false;
        int oldBg = ReadThemeHelper.getReadTheme().getBg();
        int oldMenuBg = ReadThemeHelper.getReadTheme().getMenuBgColor();
        int oldLineBg = ReadThemeHelper.getReadTheme().getLineColor();
        int oldContentTextColor = ReadThemeHelper.getReadTheme().getContentFontColor();
        int oldStatuTextColor = ReadThemeHelper.getReadTheme().getStatusBarFontColor();
        final ReadTheme readTheme = ReadThemeHelper.updataReadTheme(themeType);
        if (adapter != null) {
            adapter.updata(readTheme);
        }
        final Timer timer = new Timer();
        if (isPageTurningVertical()) {
            try {
                setAnimationColor(llAutoPlay,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),1000);
                setAnimationColor(mTopLayout,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),1000);
                setAnimationColor(layContent,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),1000);
                setAnimationColor(mBottomLayout,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),1000);
                setAnimationColor(rlSecondLevelMenu,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),1000);
                setAnimationColor(mNovelViewGroup,getResources().getColor(oldBg),getResources().getColor(readTheme.getBg()),1000);
                setAnimationColor(lineOne,getResources().getColor(oldLineBg),getResources().getColor(readTheme.getLineColor()),1000);
                setAnimationColor(lineTwo,getResources().getColor(oldLineBg),getResources().getColor(readTheme.getLineColor()),1000);
                setAnimationColor(lineThree,getResources().getColor(oldLineBg),getResources().getColor(readTheme.getLineColor()),1000);
                setAnimationColor(mTopLine,getResources().getColor(oldLineBg),getResources().getColor(readTheme.getLineColor()),1000);
                setAnimationAlpha(seekbarChapter,1.0f,0.0f,300);
                setAnimationAlpha(seekbarFontSize,1.0f,0.0f,300);
                setAnimationAlpha(seekbarLight,1.0f,0.0f,300);
                if (detailsAdapter != null && mNovelViewGroup!=null
                        && detailsAdapter.getCount() > mNovelViewGroup.getCurrentItem()) {
                    SectionDetailsFragment fragment = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
                    if (fragment != null) {
                        setAnimationTextColor(fragment.getTvContent(),getResources().getColor(oldContentTextColor),getResources().getColor(readTheme.getContentFontColor()));
                        setAnimationTextColor(fragment.getTvPageNumber(),getResources().getColor(oldStatuTextColor),getResources().getColor(readTheme.getStatusBarFontColor()));
                        setAnimationAlpha(fragment.getBtnPay(),1.0f,0.0f,300);
                        setAnimationAlpha(fragment.getTvPayAllTip(),1.0f,0.0f,300);
                    }
                }
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setReadTheme(readTheme);
                                try {
                                    setAnimationAlpha(seekbarChapter,0.0f,1.0f,300);
                                    setAnimationAlpha(seekbarFontSize,0.0f,1.0f,300);
                                    setAnimationAlpha(seekbarLight,0.0f,1.0f,300);
                                    canClick = true;
                                    if (detailsAdapter != null && mNovelViewGroup!=null
                                            && detailsAdapter.getCount() > mNovelViewGroup.getCurrentItem()
                                            && detailsAdapter.getItem(mNovelViewGroup.getCurrentItem()) instanceof SectionDetailsFragment) {
                                        SectionDetailsFragment fragment = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
                                        setAnimationAlpha(fragment.getBtnPay(),0.0f,1.0f,300);
                                        setAnimationAlpha(fragment.getTvPayAllTip(),0.0f,1.0f,300);
                                    }
                                } catch (NoSuchMethodError e) {
                                    canClick = true;
                                }
                            }
                        });
                    }
                },1000);
            } catch (NoSuchMethodError e) {
                setReadTheme(readTheme);
                canClick = true;
            }

        }else{
            if (themeType == ThemeType.TYPE_DAY) {
                lay.setBackgroundResource(R.color.read_content_bg_color_night);
                try {
                    setAnimationColor(llAutoPlay,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),2000);
                    setAnimationColor(layContent,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),2000);
                    setAnimationColor(mTopLayout,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),2000);
                    setAnimationColor(mBottomLayout,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),2000);
                    setAnimationColor(rlSecondLevelMenu,getResources().getColor(oldMenuBg),getResources().getColor(readTheme.getMenuBgColor()),2000);
                    setAnimationColor(mNovelViewGroup,getResources().getColor(oldBg),getResources().getColor(readTheme.getBg()),2000);
                    setAnimationColor(lineOne,getResources().getColor(oldLineBg),getResources().getColor(readTheme.getLineColor()),2000);
                    setAnimationColor(lineTwo,getResources().getColor(oldLineBg),getResources().getColor(readTheme.getLineColor()),2000);
                    setAnimationColor(lineThree,getResources().getColor(oldLineBg),getResources().getColor(readTheme.getLineColor()),2000);
                    setAnimationColor(mTopLine,getResources().getColor(oldLineBg),getResources().getColor(readTheme.getLineColor()),2000);
                    setAnimationAlpha(seekbarChapter,1.0f,0.0f,300);
                    setAnimationAlpha(seekbarFontSize,1.0f,0.0f,300);
                    setAnimationAlpha(seekbarLight,1.0f,0.0f,300);
                    setAnimationAlpha(novel_left_to_right,1.0f,0.2f,100);
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    setReadTheme(readTheme);
                                    try {
                                        setAnimationAlpha(novel_left_to_right,0.2f,1.0f,2000);
                                        setAnimationAlpha(seekbarChapter,0.0f,1.0f,300);
                                        setAnimationAlpha(seekbarFontSize,0.0f,1.0f,300);
                                        setAnimationAlpha(seekbarLight,0.0f,1.0f,300);
                                        timer.schedule(new TimerTask() {
                                            @Override
                                            public void run() {
                                                canClick = true;
                                            }
                                        },2000);
                                    } catch (NoSuchMethodError e) {
                                        canClick = true;
                                    }
                                }
                            });
                        }
                    },100);
                } catch (NoSuchMethodError e) {
                    setReadTheme(readTheme);
                    canClick = true;
                }
            }else{
                canClick = true;
                setReadTheme(readTheme);
            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if(isTurnOnVolumeKey){
                    pageDown();
                    return true;
                }else{
                    return false;
                }
            case KeyEvent.KEYCODE_VOLUME_UP:
                if(isTurnOnVolumeKey){
                    pageUp();
                    return true;
                }else{
                    return false;
                }
            case KeyEvent.KEYCODE_BACK:
                if (isAutoPlay) {
                    if (isAutoPlayMuneVisiable) {
                        setAutoPlayMuneVisiable(!isAutoPlayMuneVisiable);
                    }else{
                        setAutoPlay();
                    }
                    return true;
                }else{
                    return super.onKeyDown(keyCode, event);
                }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setAutoPlay() {
        if (sectionDetailsLRFragmentNew == null) {
            return;
        }
        isAutoPlay = !isAutoPlay;
        if (isAutoPlay) {
            setScreenUnLock(true);
            viewPlay.setVisibility(View.VISIBLE);
            int speed = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_AUTO_READ_ALL_TIME, this, 20);
            speed = formatSpeed(speed);
            sectionDetailsLRFragmentNew.updateSpeed(speed*1000);
            hideMenu();
        }else{
            exitAutoPlay();
        }
        sectionDetailsLRFragmentNew.setAutoPlay(isAutoPlay);
    }

    public void exitAutoPlay() {
        viewPlay.setVisibility(View.GONE);
        setAutoPlayMuneVisiable(false);
        boolean isUnLock = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SharedPreferencesKey.SP_READ_PAGE_READ_UNLOCK_SCREEN,
                this, false);
        setScreenUnLock(isUnLock);
        Toast.makeText(this, "退出自动阅读", Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if(isTurnOnVolumeKey){
                    return true;
                }else{
                    return false;
                }
            case KeyEvent.KEYCODE_VOLUME_UP:
                if(isTurnOnVolumeKey){
                    return true;
                }else{
                    return false;
                }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void finish() {
        if (has_fav) {
            super.finish();
        }else{
            int readTime = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SPKey.NOVEL_READ_TIMES+novelId,this,0);
            if (readTime < 0) {
                super.finish();
            } else if (readTime > 2 || readArticleNum > 4) {
                //弹出收藏框
                toastCollectDialog();
                //将值设置成-1，不再弹出
                DiaoBaoSharedPreferences.setSharedPreferencesValueToInt(SPKey.NOVEL_READ_TIMES+novelId,-1,this);
            }else{
                super.finish();
            }
        }
    }

    private void toastCollectDialog() {
        DoubleBtnTiptDialog dialog = new DoubleBtnTiptDialog(this,R.style.updateDialog,
                "喜欢就收藏吧","收藏后，作品更新将第一时间收到提醒","以后再说", "收藏作品",
                () -> {
                    finish();
                }, () -> {
                    handlerCollect();
                    Observable.timer(300, TimeUnit.MILLISECONDS)
                            .compose(RxJavaHelper.observeOnMainThread(getThisActivity()))
                            .subscribe(aLong -> finish());
        });
        dialog.show();
    }

    /**
     * 向下翻页
     */
    private void pageDown() {
        if(detailsAdapter != null && detailsAdapter.getCount() > 0){
            SectionDetailsFragment sdfOne = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
            sdfOne.pageDown();
        }
        if (sectionDetailsLRFragmentNew != null) {
            sectionDetailsLRFragmentNew.pageDown();
        }
    }

    /**
     * 向上翻页
     */
    private void pageUp() {
        if(detailsAdapter != null && detailsAdapter.getCount() > 0){
            SectionDetailsFragment sdfOne = (SectionDetailsFragment) detailsAdapter.getItem(mNovelViewGroup.getCurrentItem());
            sdfOne.pageUp();
        }

        if (sectionDetailsLRFragmentNew != null) {
            sectionDetailsLRFragmentNew.pageUp();
        }
    }

    public void topBack(View view) {
        finish();
    }

    public void enter_novel_comment(View view) {
        enterNovelComment();
    }

    public void enter_novel_list(View view) {
        enterNovelList();
    }


    public static void startActivity(Context context,
                                     String novelId,
                                     String sectionId,
                                     boolean hasCollect,
                                     int monthTicketSum,
                                     String activityName) {
        Intent intent = new Intent(context, NovelSectionDetailsActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (sectionId != null && !sectionId.isEmpty() && !sectionId.equals("0")) {
            intent.putExtra(Constant.ARTICLE_ID, sectionId);
        }
        intent.putExtra(Constant.ARTICLE_NOVELID, novelId);
        intent.putExtra("activity", activityName);
        intent.putExtra(Constant.HAS_FAV,  hasCollect);
        intent.putExtra(Constant.MONTH_TICKET_SUM,  monthTicketSum);
        context.startActivity(intent);
    }
}
